Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 490
sites Avatar asked May 24 '13 05:05

sites


1 Answers

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.

like image 78
mu is too short Avatar answered Oct 14 '22 11:10

mu is too short