Read more

Cast an ActiveRecord to a subclass or superclass

Henning Koch
April 04, 2011Software engineer at makandra GmbH

Note: ActiveRecord::Base#becomes has a lot of quirks and inconsistent behavior. You probably want to use ActiveType.cast instead.


Illustration online protection

Rails professionals since 2007

Our laser focus on a single technology has made us a leader in this space. Need help?

  • We build a solid first version of your product
  • We train your development team
  • We rescue your project in trouble
Read more Show archive.org snapshot

ActiveRecord models have with a method becomes(klass) Show archive.org snapshot which you can use to cast the record into an instance of its subclasses or superclass. This is useful because some parts of Rails reflect on the class of an instance, e.g. to decide which partial to render:

Returns an instance of the specified klass with the attributes of the current record. This is mostly useful in relation to single-table inheritance structures where you want a subclass to appear as the superclass. This can be used along with record identification in Action Pack to allow, say, Client < Company to do something like render :partial => @client.becomes(Company) to render that instance using the companies/company partial instead of clients/client.

Note: The new instance will share a link to the same attributes as the original class. So any change to the attributes in either instance will affect the other.

Hat tip to PavelTyk Show archive.org snapshot for pointing out this method in his Code Snippets Show archive.org snapshot .

Posted by Henning Koch to makandra dev (2011-04-04 10:50)