Question

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

Was it helpful?

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top