How can I overwrite a getter method in an ActiveRecord model?
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
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
I would like to add another option for overwriting getter method, which is simply :super.
def name name_trans || superend
this works not just on attributes getter method, but also associations getter methods, too。