ActiveRecord: Overwriting attribute=
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
Filed Under: Ruby on Rails
Ben Mabey said,
Wrote on January 24, 2008 @ 4:24 pm
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.
Jimmy'z said,
Wrote on January 24, 2008 @ 4:44 pm
Cool! Thanks Ben.