class Country < ActiveRecord::Base
#alias_method :name, :langEN # here fails
#alias_method :name=, :langEN=
#attr_accessible :name
def name; langEN end # here works
end
在第一次调用 alias_method
时失败:
NameError: undefined method `langEN' for class `Country'
我的意思是当我执行 Country.first
时它失败了。
但在控制台中,我可以成功调用 Country.first.langEN
,并且看到第二个调用也有效。
我错过了什么?
最佳答案
ActiveRecord 使用 method_missing
(AFAIK 通过 ActiveModel::AttributeMethods#method_missing
)在第一次调用时创建属性访问器和修改器方法。这意味着当您调用 alias_method
时没有 langEN
方法。和 alias_method :name, :langEN
因您的“未定义方法”错误而失败。明确地做别名:
def name
langEN
end
之所以有效,是因为 langEN
方法将在您第一次尝试调用它时创建(通过 method_missing
)。
Rails 提供 alias_attribute
:
alias_attribute(new_name, old_name)
Allows you to make aliases for attributes, which includes getter, setter, and query methods.
您可以改用它:
alias_attribute :name, :langEN
内置的method_missing
将了解使用alias_attribute
注册的别名,并将根据需要设置适当的别名。
关于ruby-on-rails - 为什么 alias_method 在 Rails 模型中失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16727976/