How can I overwrite a getter method in an ActiveRecord model?
Overriding the getter and using read_attribute
does not work for associations, but you can use alias_method_chain
instead.
def name_with_override
name_trans || name_without_override
end
alias_method_chain :name, :override
Update: The preferred method according to the Rails Style Guide is to use self[:name]
instead of read_attribute
and write_attribute
. I would encourage you to skip my answer and instead prefer this one.
You can do it exactly like that, except that you need to use read_attribute
to actually fetch the value of the name attribute and avoid the recursive call to the name
method:
def name
name_trans || read_attribute(:name)
end
The Rails Style Guide recommends using self[:attr]
over read_attribute(:attr)
.
You can use it like this:
def name
name_trans || self[:name]
end
I would like to add another option for overwriting getter method, which is simply :super.
def name
name_trans || super
end
this works not just on attributes getter method, but also associations getter methods, too。