Rails attribute alias

Posted by Dr1Ku on Stack Overflow See other posts from Stack Overflow or by Dr1Ku
Published on 2010-05-15T13:49:44Z Indexed on 2010/05/15 13:54 UTC
Read the original article Hit count: 168

Filed under:
|

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 !

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about activerecord