Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Mongoid关联创建(不需要的)记录_Ruby On Rails_Mongodb_Mongoid - Fatal编程技术网

Ruby on rails Mongoid关联创建(不需要的)记录

Ruby on rails Mongoid关联创建(不需要的)记录,ruby-on-rails,mongodb,mongoid,Ruby On Rails,Mongodb,Mongoid,我不明白为什么Mongoid在一个协会创造了一个新记录。我正在仔细阅读代码,但我从未见过这样的事情。我做了一个测试并精简了代码。我把录像机留着以防万一 it "should not create a duplicate entry for MT" do state = PolcoGroup.create(type: :state, name: 'MT', active: true) s = state.get_senators state.junior_senator =

我不明白为什么Mongoid在一个协会创造了一个新记录。我正在仔细阅读代码,但我从未见过这样的事情。我做了一个测试并精简了代码。我把录像机留着以防万一

it "should not create a duplicate entry for MT" do state = PolcoGroup.create(type: :state, name: 'MT', active: true) s = state.get_senators state.junior_senator = s[:state_junior_senator] # !!!!! this creates a new record state.senior_senator = s[:state_senior_senator] # !!!!! so does this line expect(Legislator.all.size).to eql(2) # actually equals 4 -- each association creates a new record end result is: Legislator.all.map(&:sortname) => ["Tester, Jon (Sen.) [D-MT]", "Walsh, John (Sen.) [D-MT]", "Walsh, John (Sen.) [D-MT]", "Tester, Jon (Sen.) [D-MT]"] ## models class PolcoGroup include Mongoid::Document include Mongoid::Timestamps include VotingMethods include DistrictMethods extend DistrictClassMethods include StateMethods field :name, :type => String ... # STATE RELATIONSHIPS ----------------------------- has_one :junior_senator, class_name: "Legislator", inverse_of: :jr_legislator_state has_one :senior_senator, class_name: "Legislator", inverse_of: :sr_legislator_state ... end class Legislator include Mongoid::Document include Mongoid::Timestamps # the following fields are directly from govtrack field :govtrack_id, type: Integer field :bioguideid, type: String ... belongs_to :jr_legislator_state, class_name: "PolcoGroup", inverse_of: :junior_senator belongs_to :sr_legislator_state, class_name: "PolcoGroup", inverse_of: :senior_senator ... end module StateMethods def get_senators ... # just returns the following {state_senior_senator: senators.first, state_junior_senator: senators.last} end end
您可以在这里看到更多代码:

好的-永远不要做我所做的事情。我把一个旧版本的mongo作为测试数据库,然后进行上述操作。当然,它工作不正常。

在查看代码时,我看到调用了Mongoid::Relations::Accessors,并调用了build,其描述为:构建相关文档并创建关系,除非文档为nil,否则在此文档上设置关系。该记录是由:relation=create\u relationobject创建的,metadataSee:我几乎在一年前就遇到了同样的问题: