Duplicate Records created from Association

与世无争的帅哥 提交于 2019-12-14 04:06:09

问题


I am using Mongoid, Rails and Fabrications and at a total loss with how this is happening. Any thoughts very appreciated, but I know this pretty complicated. I just want to fabricate a user and have only four joined groups, but I keep getting eight loaded.

Here is the relevant section of my code

@user1 = Fabricate.build(:registered)
@user1.joined_groups << [common_group,
                             cali_group,
                             ca46,
                             Fabricate(:polco_group, {:name => "Gang of 13", :type => :custom})]

When I run @user1.joined_groups.size I get 4, but when I do @user1.joined_groups.map(&:name), I get 8 records:

#<PolcoGroup _id: 1  ... member_ids: [], follower_ids: []>
#<PolcoGroup _id: 1  ... member_ids: [], follower_ids: []>
#<PolcoGroup _id: 1  ... member_ids: [], follower_ids: []>
#<PolcoGroup _id: 1  ... member_ids: [], follower_ids: []>
#<PolcoGroup _id: 1  ... member_ids: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], follower_ids: [1, 1]>
#<PolcoGroup _id: 1  ... member_ids: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], follower_ids: [1, 1]>
#<PolcoGroup _id: 1  ... member_ids: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], follower_ids: [1, 1]>
#<PolcoGroup _id: 1  ... member_ids: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], follower_ids: [1, 1]>

(where i have replaced all BSON::ObjectId('4eab3ca5f11aac2701000009') statements with ones and removed a lot of the middle code.

The full set of code is available here: https://gist.github.com/1323984

Most bizzarre simply calling map might be causing the problem.

    puts "just created user with these groups:"
    puts @user1.joined_groups.map(&:name)
    puts "then secondly"
    puts @user1.joined_groups.map(&:name)

Generates this (!):

just created user with these groups:
Dan Cole
CA
CA46
Gang of 13
then secondly
Dan Cole
CA
CA46
Gang of 13
Dan Cole
CA
CA46
Gang of 13

Thanks for any insight! After repeated attempts, I can't figure out a way in terminal to duplicate this, so I am suspecting the Fabrication gem. (Update: nope, I get this error with standard mongoid objects, so I am totally blaming mongoid.)

Tim


回答1:


I think the problem might simply be that you are not pushing the groups onto the user correctly. Try using concat or separately shoveling them.

@user1.joined_groups.concat([common_group,
                         cali_group,
                         ca46,
                         Fabricate(:polco_group, {:name => "Gang of 13", :type => :custom})])


来源:https://stackoverflow.com/questions/7936489/duplicate-records-created-from-association

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