Notes to self

What is ActiveRecord becomes from Rails

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

becomes

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

Here’s how:

class Car
  ...
end

class Honda < Car
  ...
end

# 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.

Check out my book
Interested in Ruby on Rails default testing stack? Take Minitest and fixtures for a spin with my latest book.

Get Test Driving Rails while it's in prerelease.

by Josef Strzibny
RSS