Mongoid has_and_belongs_to_many associations

守給你的承諾、 提交于 2019-12-12 11:03:46

问题


I trying to get mongoid to save associations, but I can only get one side to work. If I have the following test.

  test "should add a user as a follower when a user follows the group" do                                                                                                                                        
    @cali_group.followers = []                                                                                                                                                
    @user1.followed_groups << @cali_group                                                                                                                                                  
    assert_equal 1, @user1.followed_groups.count
    assert_equal 1, @cali_group.followers.count
  end

Which is failing, because @cali_group.followers is []. I've been working with this for awhile, tried @cali_group.reload. But it looks like the only way to do this in my code is to work both ends of the join, i.e. @cali_group.followers << @user1. I can do that in my code if I have to.

The models for polco_group and user are here: https://gist.github.com/1195048

Full test code is here: https://gist.github.com/1195052


回答1:


It can be that: https://github.com/mongoid/mongoid/issues/1204




回答2:


Very late to the show. Using Mongoid 4.0.2 here. The issue is troubling me as well.

The link by @sandrew is no longer valid. A similar issue was reported here: http://github.com/mongodb/mongoid/pull/3604

The workaround that I found was:

@cali_group.followers = []
@cali_group.follower_ids # Adding this line somehow does something to the cache
@user1.followed_groups << @cali_group

Found this workaround by adding a before_save in the Group class and observing self.changes. Without this line, the follower_ids member changes from nil to []. However after adding the line, the correct ID of the user is received and set. Hope that helps any future reader.



来源:https://stackoverflow.com/questions/7308539/mongoid-has-and-belongs-to-many-associations

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