Mongoid has_and_belongs_to_many association

I am 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

What happens because @ cali_group.followers []. I worked with this for a while, tried it @cali_group.reload. But it seems that the only way to do this in my code is to work at both ends of the connection, i.e. @cali_group.followers << @user1. I can do this in my code if I need to.

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

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

+5
source share
2 answers
+1
source

Very late on the show. It uses Mongoid 4.0.2. The problem also bothers me.

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

The workaround I found was:

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

This workaround was discovered by adding before_save to the Group class and abiding self.changes. Without this line, the member follower_idschanges from nilto []. However, after adding the line, the correct user ID is accepted and set. Hope this helps any future reader.

0
source

All Articles