Mongoid的has_and_belongs_to_many关联

5

我正在尝试让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 和 user 的模型在这里:https://gist.github.com/1195048 完整的测试代码在这里:https://gist.github.com/1195052

1
你在用户端没有设置 :inverse_of,这可能导致了你的问题。 - rubish
好的,我会调查一下。 - bonhoffer
嗯……还是不行——但无论如何都需要改进。 - bonhoffer
2个回答

1

是的,它已经测试过了,这是一个缓存问题。 - bonhoffer
1
@sandrew提供的链接已经失效。 这里有一个类似的问题报告: https://github.com/mongodb/mongoid/pull/3604 - Akshay Rao

0

非常晚才来参加。我在这里使用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 被接收并设置。希望这能帮助未来的读者。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接