2014-12-29 54 views
0

我不知道爲什麼Mongoid正在創建關聯中的新記錄。我正密切關注代碼,但我從來沒有見過這樣的事情。我做了一個測試,並縮減了代碼。我留下了錄像機以防萬一它可能有關係。Mongoid Association創建(不需要的)記錄

 
    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 

你可以看到更多的代碼在這裏:https://gist.github.com/tbbooher/d892f5c234053990da70

+0

在看代碼 - 我看到Mongoid :: Relations :: Accessors被調用,並且__build__被調用,它被描述爲:「#構建相關文檔並創建關係,除非 #文檔爲零,然後在這個文件上設置關係。「記錄創建者:relation = create_relation(object,metadata) – bonhoffer

+0

看到這個:https://github.com/mongoid/mongoid/blob/1f3875a0a98a089f5d54331191ea9bf8a2c3e755/lib/mongoid/relations/accessors.rb#L11-L28 – bonhoffer

+0

我似乎幾乎一年前有同樣的問題:http://stackoverflow.com/questions/7936489/duplicate-records-created-from-association – bonhoffer

回答

0

OK - 永遠做我所做的。我將一個老版本的mongo作爲測試數據庫,然後進行上述操作。當然,它不能正常工作。

相關問題