How can I overwrite a getter method in an ActiveRecord model?

I'm trying to overwrite a getter method for an ActiveRecord model. I have an attribute called name in the model Category, and I'd like to be able to do something like this:

def name
  name_trans || name
end

If name_trans attribute is not nil, then return it, else return name attribute. How would I do this?

This should then be called normally like this:

@category.name

Solution 1:

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

Solution 2:

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