What is ActiveRecord becomes from Rails

Have you heard about the ActiveRecord becomes method from Rails? Maybe it’ll come handy one day.


The #becomes method can be used on any ActiveRecord model to become a different class instantly.

Here’s how:

class Car

class Honda < Car

# Later

@honda = Honda.new(..)
@i_am_a_car_instance = @honda.becomes(Car)

Any model can become some other model on a whim with the same attributes. But why do we need #become at all?

A typical use-case would be using single table inheritance (STI) while keeping Rails conventions intact.

For example, building forms and rendering partials are derived from the instance class name which would intervene with reusing the parent model routes and partials:

# Use Car's routes
form_for @honda.becomes(Car)

# Use Car's partials
render partial: @honda.becomes(Car)

In short, #becomes helps us to pass the right object without providing the full paths and partials if they don’t match the object at hand.

← 950+ copies sold!

Learn the ins and outs of web application deployment with Ruby, Python, and Linux.

More →

← New new new

Save 100+ hours and forget international tax on your next Ruby on Rails business idea.

More →