ruby-on-rails - 为什么 alias_method 在 Rails 模型中失败

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

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/

相关文章:

ruby-on-rails - Carrierwave、Rails 4 和多次上传

html - rails 错误: Autoplay is only working sometimes for video_tag

ruby - 如果没有 arg,则针对 stdin 运行的脚本;否则输入文件=ARGV[0]

ruby-on-rails - 如何从Rails ActiveRecord获取昨天的数据

ruby-on-rails - ActiveRecord 选择列除外

ruby-on-rails - Rails 3.1 Assets 管道 : how to deal with requests to expired assets?

ruby-on-rails - 在rails中我如何委托(delegate)给一个类方法

javascript - Rails 4 jQuery 与 javascript 冲突

ruby - 如何处理 ruby​​ 中的 JSON 解析器错误

ruby-on-rails - ruby rails : Confirmation Page for ActiveRecord Object Creation