ActiveRecord: Overwriting attribute= 2

Posted by Jimmy'z on January 24, 2008

I always forget the command for doing this so I’m posting it here so I can find it easily.

If you want to overwrite accessors in rails (ActiveRecord), you will run into problems if you try to do it the same way you would with a regular Ruby object. For example, say you want to apply a transformation to an attribute as you assign it:

@person.name = 'ralph'

You always want name to be capitalized, so you would like to modify the name= method. With plain Ruby you would just do:

def name=(value)
@name = value.capitalize
end

You can’t do this with ActiveRecord, you will need to use a method named write_attribute so the method will look like:

def name=(value)
write_attribute(:name, value.capitalize)
end

There is also a read_attribute method to help with overwriting the read method on your attributes in ActiveRecord

Trackbacks

Use this link to trackback from your own site.

Comments

Leave a response

  1. Ben Mabey Thu, 24 Jan 2008 16:24:40 UTC

    You can also just call the super…. Calling the super will also help prevent API changes if for whatever unlikely reason AR changes the naming of those methods or refactored them.

    def name=(value)
    super(value.capitalize)
    end

    For reading attributes you can also use the [] operator.

  2. Jimmy'z Thu, 24 Jan 2008 16:44:23 UTC

    Cool! Thanks Ben.

Comments