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