Cast an ActiveRecord to a subclass or superclass

Updated . Posted . Visible to the public.

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


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.

Henning Koch
Last edit
Jonas Schiele
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2011-04-04 08:50)