This post originated from an RSS feed registered with Ruby Buzz
by Jay Fields.
Original Post: Rails: ActiveRecord Serialize method
Feed Title: Jay Fields Thoughts
Feed URL: http://feeds.feedburner.com/jayfields/mjKQ
Feed Description: Blog about Ruby, Agile, Testing and other topics related to software development.
On my current project we have a model with a few attributes that are instances. Generally, this is handled with a relationship (e.g. belongs_to). However, these attributes are not ActiveRecord::Base subclass instances. ActiveRecord handles this situation by providing the ActiveRecord::Base.serialize class method.
As a contrived example, imagine a UserAccount class that has a AuthorizationConfirmation instance as an attribute.
class CreateModels < ActiveRecord::Migration def self.up create_table :user_accounts do |t| t.column :authorization_confirmation, :string end end
def self.down drop_table :user_accounts end end
class UserAccount < ActiveRecord::Base serialize :authorization_confirmation, AuthorizationConfirmation end
class AuthorizationConfirmation attr_accessor :fingerprint, :key end
As you can see in the above example, the UserAccount class has the attribute authorization_confirmation. The value stored in authorization_confirmation is expected to be an instance of the AuthorizationConfirmation class.