[英]Why alias_method fails in Rails model
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
(通過ActiveModel::AttributeMethods#method_missing
通過AFAIK)在首次調用它們時創建屬性訪問器和更改器方法。 這意味着,當您調用alias_method
和alias_method :name, :langEN
時,沒有langEN
方法失敗,並顯示“未定義方法”錯誤。 明確地進行別名:
def name
langEN
end
之所以可以工作,是因為第一次嘗試調用langEN
方法時( method_missing
會創建該方法)。
Rails提供了alias_attribute
:
alias_attribute(新名稱,舊名稱)
允許您為屬性(包括getter,setter和查詢方法)創建別名。
您可以改用:
alias_attribute :name, :langEN
內置的method_missing
將了解在alias_attribute
注冊的別名,並將根據需要設置適當的別名。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.