开发者

Rails attribute alias

开发者 https://www.devze.com 2022-12-30 15:20 出处:网络
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)

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 !


You could achieve this by using :items instead of :some_model_a_sub_model_items as the name of the relation, and explicitly specifying the name of the class you're referring to using the :class_name parameter:

# An ActiveRecord Class named SomeModelASubModel (some_model_a_sub_model.rb)
class SomeModelASubModel < ActiveRecord::Base
  has_many :items, :class_name => "SomeModelASubModelItems"
end

See the ActiveRecord docs for more info.

0

精彩评论

暂无评论...
验证码 换一张
取 消