Ruby on Rails: Override Attribute Assignment 1

Posted by Tadman Thu, 05 Jul 2007 20:07:00 GMT

ActiveRecord models used to provide access to their internal attribute data through the attributes method, but this doesn’t seem to be the case any longer. Have a look at the current source code and you can see why. The attribute hash is cloned before being returned, so changes aren’t applied.

So the old method of reassigning is no longer applicable:

m = MyModel.create(:name => 'test')
m.attributes[:name] = 'value'   # Assigns to a clone of m's @attributes
m.name
 # => 'test'

This limits your options when trying to re-define an assignment method, but there is still a way. For example, to trigger some behaviour when a value is assigned, you can do this:

def name=(value)
        # Always force to lower-case
        super(value.downcase)
end

Calling the base class method of the same name will allow ActiveRecord to handle the assignment properly, and there’s still a way to extend the basic functionality in a model.