Rails attribute alias
- by Dr1Ku
Hi,
I was just wondering if it's possible to "rename" an association in Rails. Let's assume :
# An ActiveRecord Class named SomeModelASubModel (some_model_a_sub_model.rb)
class SomeModelASubModel < ActiveRecord::Base
has_many :some_model_a_sub_model_items
end
# An ActiveRecord Class named SomeModelASubModelItem (some_model_a_sub_model_item.rb)
class SomeModelASubModelItem < ActiveRecord::Base
belongs_to :some_model_a_sub_model
end
At this point, calling some_model.items, where some_model is an instance of the SomeModelASubModel Class would trigger an undefined method error.
What is the best practice for making this happen though, e.g. :
# With a method_alias or something, would it be possible to :
some_model = SomeModelASubModel.first # for instance
items = some_model.items
# For the reason stated, this doesn't work, one has to call :
items = some_model.some_model_a_sub_model_items
Is such a shorthand possible ?
Thank you in advance !