Rails attribute attribute

I'm just wondering if the association can be "renamed" in Rails. Let's pretend that

# 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, will cause an undefined method error.

What is the best practice for this though, for example,

# 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 reduction possible?

Thank you in advance!

+3
source share
1 answer

This can be done by using the name of the relation :itemsinstead :some_model_a_sub_model_itemsand explicitly specifying the name of the class you are accessing using the parameter :class_name:

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

See ActiveRecord Docs for more information .

+4
source

Source: https://habr.com/ru/post/1745571/


All Articles