如何覆盖ActiveRecord模型中的getter方法? [英] How can I overwrite a getter method in an ActiveRecord model?

查看:91
本文介绍了如何覆盖ActiveRecord模型中的getter方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试覆盖ActiveRecord模型的getter方法.我在模型Category中有一个名为name的属性,我希望能够执行以下操作:

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

如果name_trans属性不是nil,则返回它,否则返回name属性.我该怎么办?

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

通常应这样称呼它:

@category.name

推荐答案

Rails样式指南建议在read_attribute(:attr)上使用self[:attr].

您可以像这样使用它:

def name
  name_trans || self[:name]
end

这篇关于如何覆盖ActiveRecord模型中的getter方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆