Mongoid Association创建(不需要的)记录

时间:2014-12-29 22:40:48

标签: 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 = 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

1 个答案:

答案 0 :(得分:0)

好的 - 永远不要做我做的事。我将旧版本的mongo作为测试数据库,然后执行上述操作。当然它无法正常工作。