-
Type: Bug
-
Resolution: Duplicate
-
Priority: Major - P3
-
None
-
Affects Version/s: 7.1.2
-
Component/s: Associations
-
None
I have two models that are defined as follows.
class User include Mongoid::Document has_many :offers, class_name: 'Offer', inverse_of: :buyer has_many :cobuyer_offers, class_name: 'Offer', inverse_of: :cobuyer end class Offer include Mongoid::Document belongs_to :buyer, class_name: "User", inverse_of: :offers belongs_to :cobuyer, class_name: "User", inverse_of: :cobuyer_offers belongs_to :modifier, class_name: "User", inverse_of: nil end Offer.create!(buyer:User.new,cobuyer:User.new,modifier:User.new)
When setting modifier on Offer, it throws the following error:
Ambiguous associations #<Mongoid::Association::Referenced::HasMany:0x00007fe4e13faac0 @owner_class=User, @name=:offers, @options={:class_name=>"Offer", :inverse_of=>:buyer}, @extension=nil, @module_path="", @polymorphic=false, @validate=true, @class_name="Offer", @primary_key="_id", @klass=Offer, @default_foreign_key_field="buyer_id", @foreign_key="buyer_id">, #<Mongoid::Association::Referenced::HasMany:0x00007fe4e1407748 @owner_class=User, @name=:cobuyer_offers, @options={:class_name=>"Offer", :inverse_of=>:cobuyer}, @extension=nil, @module_path="", @polymorphic=false, @validate=true, @class_name="Offer", @primary_key="_id", @klass=Offer, @default_foreign_key_field="cobuyer_id", @foreign_key="cobuyer_id"> defined on User. summary: When Mongoid attempts to set an inverse document of an association in memory, it needs to know which association it belongs to. When setting :modifier, Mongoid looked on the class Offer for a matching association, but multiples were found that could potentially match: #<Mongoid::Association::Referenced::HasMany:0x00007fe4e13faac0 @owner_class=User, @name=:offers, @options={:class_name=>"Offer", :inverse_of=>:buyer}, @extension=nil, @module_path="", @polymorphic=false, @validate=true, @class_name="Offer", @primary_key="_id", @klass=Offer, @default_foreign_key_field="buyer_id", @foreign_key="buyer_id">, #<Mongoid::Association::Referenced::HasMany:0x00007fe4e1407748 @owner_class=User, @name=:cobuyer_offers, @options={:class_name=>"Offer", :inverse_of=>:cobuyer}, @extension=nil, @module_path="", @polymorphic=false, @validate=true, @class_name="Offer", @primary_key="_id", @klass=Offer, @default_foreign_key_field="cobuyer_id", @foreign_key="cobuyer_id">. resolution: On the :modifier association on Offer you must add an :inverse_of option to specify the exact association on User that is the opposite of :modifier.
It seems to me that the modifier relation should not throw an ambiguous relationship error because it has inverse_of set to nil.
- duplicates
-
MONGOID-5149 Do not try to detect inverse if it is explicitly set to nil
- Closed
- is related to
-
MONGOID-4962 Document inverse_of: nil in tutorial
- Backlog