Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

ruby - 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

In first call alias_method fails with:

NameError: undefined method `langEN' for class `Country'

I mean it fails when I do for example Country.first.

But in console I can call Country.first.langEN successfully, and see that second call also works.

What am I missing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

works because the langEN method will be created (by method_missing) the first time you try to call it.

Rails offers alias_attribute:

alias_attribute(new_name, old_name)

Allows you to make aliases for attributes, which includes getter, setter, and query methods.

which you can use instead:

alias_attribute :name, :langEN

The built-in method_missing will know about aliases registered with alias_attribute and will set up the appropriate aliases as needed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...