开发者

Mongoid has_and_belongs_to_many associations

开发者 https://www.devze.com 2023-04-02 06:48 出处:网络
I trying to get mongoid to save associations, but I can only get one side to work. If I have the following test.

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                                                                                                     开发者_StackOverflow                                   
    @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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号