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?
ActiveRecord uses
method_missing(AFAIK viaActiveModel::AttributeMethods#method_missing) to create attribute accessor and mutator methods the first time they're called. That means that there is nolangENmethod when you callalias_methodandalias_method :name, :langENfails with your "undefined method" error. Doing the aliasing explicitly:works because the
langENmethod will be created (bymethod_missing) the first time you try to call it.Rails offers
alias_attribute:which you can use instead:
The built-in
method_missingwill know about aliases registered withalias_attributeand will set up the appropriate aliases as needed.