0
votes

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
In watching the code -- I see that Mongoid::Relations::Accessors is called and that build is called which is described as: "# Builds the related document and creates the relation unless the # document is nil, then sets the relation on this document." The record was created by: relation = create_relation(object, metadata)bonhoffer
I seemed to have the same problem almost a year ago: stackoverflow.com/questions/7936489/…bonhoffer

1 Answers

0
votes

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.