如何在 ActiveRecord 模型中覆盖 getter 方法?

我试图为 ActiveRecord 模型覆盖一个 getter 方法。在模型 Category中,我有一个名为 name的属性,我希望能够这样做:

def name
name_trans || name
end

如果 name_trans属性不是 nil,那么返回它,否则返回 name属性?

这通常应该这样称呼:

@category.name
55828 次浏览

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

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

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

If you using store attributes like this

store :settings, accessors: [:volume_adjustment]

or using gems like hstore_accessor gem link

So you ended up using store method on model, then to override those method you can't use self.read_attribute, you must use instead super like that:

def partner_percentage
super.to_i || 10
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。

If someone want update the value after name_trans in getter method, you could use self[:name]=.

def name
self[:name] = name_trans || self[:name]
# don't do this, it will cause endless loop
# update(name: name_trans)
end

You can use Rails read_attribute method. Rails docs