问题描述
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
失败:
In first call alias_method
fails with:
NameError: undefined method `langEN' for class `Country'
我的意思是当我执行例如 Country.first
时它会失败.
I mean it fails when I do for example Country.first
.
但在控制台中我可以成功调用 Country.first.langEN
,并且看到第二个调用也有效.
But in console I can call Country.first.langEN
successfully, and see that second call also works.
我错过了什么?
推荐答案
ActiveRecord 使用 method_missing
(AFAIK 通过 ActiveModel::AttributeMethods#method_missing
) 以在第一次调用时创建属性访问器和修改器方法.这意味着当您调用 langEN 方法>alias_method
和 alias_method :name, :langEN
因未定义方法"错误而失败.明确地做别名:
ActiveRecord uses method_missing
(AFAIK via ActiveModel::AttributeMethods#method_missing
) to create attribute accessor and mutator methods the first time they're called. That means that there is no langEN
method when you call alias_method
and alias_method :name, :langEN
fails with your "undefined method" error. Doing the aliasing explicitly:
def name
langEN
end
之所以有效,是因为 langEN
方法将在您第一次尝试调用时创建(通过 method_missing
).
works because the langEN
method will be created (by method_missing
) the first time you try to call it.
Rails 提供 alias_attribute
:
Rails offers alias_attribute
:
alias_attribute(new_name, old_name)
允许您为属性创建别名,包括 getter、setter 和查询方法.
Allows you to make aliases for attributes, which includes getter, setter, and query methods.
你可以改用:
alias_attribute :name, :langEN
内置的method_missing
会知道使用alias_attribute
注册的别名,并会根据需要设置适当的别名.
The built-in method_missing
will know about aliases registered with alias_attribute
and will set up the appropriate aliases as needed.
这篇关于为什么 alias_method 在 Rails 模型中失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!