Mongoid Association Creating (unwanted) Records

若如初见. 提交于 2019-12-12 03:23:15

问题


I'm at a loss to why Mongoid is creating a new record in an association. I'm stepping closely through the code, but I've never seen anything like this. I've made a test and slimmed down the code. I left the VCR in just in case it might be related.

  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

You can see more code here: https://gist.github.com/tbbooher/d892f5c234053990da70


回答1:


OK -- never do what I did. I was pulling in an old version of mongo as a test database and then conducting the above. Of course it wasn't working correctly.



来源:https://stackoverflow.com/questions/27697076/mongoid-association-creating-unwanted-records

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!