为什么Alias_method在Rails模型中失败 [英] Why alias_method fails in Rails model

查看:103
本文介绍了为什么Alias_method在Rails模型中失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 (通过 ActiveModel :: AttributeMethods#method_missing ),以便在首次调用它们时创建属性访问器和mutator方法。这意味着,当您调用 langEN 方法 rel = noreferrer> alias_method alias_method:name,:langEN 失败,您的 undefined方法错误。显式地进行别名:

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模型中失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆