Mongoid: link to the same model more than through has_many

I would like to be able to refer to a model (has_many relation) more than once in the same model. For example, given the following models:

class MyModel include Mongoid::Document field :name, type: String has_many :main_efforts, :class_name => 'Effort', as: :effortable, dependent: :delete, autosave: true has_many :secondary_efforts, :class_name => 'Effort', as: :effortable, dependent: :delete, autosave: true validates_presence_of :name end class Effort include Mongoid::Document field :name, type: String belongs_to :effortable, polymorphic: true validates_presence_of :name end 

As you can see, the Effort model is referenced twice. Initially, my Effort model was not polymorphic, but it seemed like Mongoid was unable to determine which collection (main_efforts or secondary_efforts) was involved. So I made it polymorphic. However, making it polymorphic, my main_efforts and secondary_efforts fields are always an empty array.

What is the correct way to refer to a polymorphic model more than once in the same model (if a polymorphic model is required)?

+4
source share
1 answer

It revealed:

 class MyModel include Mongoid::Document field :name, type: String has_many :main_efforts, :class_name => 'Effort', dependent: :delete, autosave: true, :inverse_of => :main_effort has_many :secondary_efforts, :class_name => 'Effort', dependent: :delete, autosave: true, :inverse_of => :secondary_effort validates_presence_of :name end class Effort include Mongoid::Document field :name, type: String belongs_to :main_effort, :class_name => 'Conop', :inverse_of => :main_efforts belongs_to :secondary_effort, :class_name => 'Conop', :inverse_of => :secondary_efforts validates_presence_of :name end 
+6
source

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


All Articles