【问题标题】:Why alias_method fails in Rails model为什么 alias_method 在 Rails 模型中失败
【发布时间】:2013-05-24 05:05:38
【问题描述】:
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,并且看到第二个调用也有效。

我错过了什么?

【问题讨论】:

    标签: ruby-on-rails ruby activerecord rails-activerecord alias-method


    【解决方案1】:

    ActiveRecord 使用method_missing(AFAIK 通过ActiveModel::AttributeMethods#method_missing)在它们第一次被调用时创建属性访问器和修改器方法。这意味着当您调用 alias_method 和 alias_method :name, :langEN 时没有 langEN 方法,您的“未定义方法”错误会失败。显式地做别名:

    def name
      langEN
    end
    

    因为langEN 方法将在您第一次尝试调用时创建(由method_missing)。

    Rails 提供alias_attribute:

    别名属性(新名称,旧名称)

    允许您为属性创建别名,包括 getter、setter 和查询方法。

    你可以用它来代替:

    alias_attribute :name, :langEN
    

    内置的method_missing 会知道alias_attribute 注册的别名,并会根据需要设置适当的别名。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-21
      • 1970-01-01
      • 1970-01-01
      • 2021-01-20
      • 2012-07-13
      • 1970-01-01
      • 1970-01-01
      • 2014-04-12
      相关资源
      最近更新 更多