Mongoid has_and_belongs_to_many关联

我试图让mongoid保存联想,但我只能让一方工作。 如果我有以下测试。

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 

哪个失败了,因为@ cali_group.followers是[]。 我已经使用了一段时间,尝试了@cali_group.reload 。 但看起来在我的代码中执行此操作的唯一方法是使用连接的两端,即@cali_group.followers << @user1 。 如果必须的话,我可以在我的代码中这样做。

polco_group和用户的模型如下: https ://gist.github.com/1195048

完整的测试代码在这里: https : //gist.github.com/1195052

它可以是: https : //github.com/mongoid/mongoid/issues/1204

演出很晚。 在这里使用Mongoid 4.0.2。 这个问题也困扰着我。

@sandrew的链接不再有效。 这里报道了一个类似的问题: http : //github.com/mongodb/mongoid/pull/3604

我找到的解决方法是:

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

通过在Group类中添加before_save并观察self.changes到此解决方法。 如果没有这一行, follower_ids成员将从nil更改为[] 。 但是,添加该行后,将接收并设置用户的正确ID。 希望能帮助任何未来的读者。