HABTM mongoid 关注者/关注者
Mongoid 附带了 habtm 上的 .push,它在两个方向上设置了 habtm 关系。尽管删除将 #delete 关联记录,但没有记录的方法可以仅删除我见过的关系。有更好的方法吗?
有没有更好的方法来保证唯一性?
has_and_belongs_to_many :following, {class_name: 'User', inverse_of: :followers, inverse_class_name: 'User'}
has_and_belongs_to_many :followers, {class_name: 'User', inverse_of: :following, inverse_class_name: 'User'}
def follow!(user)
self.following.push(user) # this pushes the inverse as well
self.following_ids.uniq!
self.save!
user.follower_ids.uniq!
user.save!
end
def unfollow!(user)
self.following.delete(user.id)
self.save!
user.followers.delete(self.id)
user.save!
end
Mongoid ships with .push on a habtm, which sets a habtm relationship in both directions. Although delete will #delete an associated record, there's no documented way to delete only a relationship that I have seen. Is there a better way of doing this?
Is there a better way of ensuring uniqueness?
has_and_belongs_to_many :following, {class_name: 'User', inverse_of: :followers, inverse_class_name: 'User'}
has_and_belongs_to_many :followers, {class_name: 'User', inverse_of: :following, inverse_class_name: 'User'}
def follow!(user)
self.following.push(user) # this pushes the inverse as well
self.following_ids.uniq!
self.save!
user.follower_ids.uniq!
user.save!
end
def unfollow!(user)
self.following.delete(user.id)
self.save!
user.followers.delete(self.id)
user.save!
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
以下代码对我来说效果很好(mongoid 2.3.x):
没有
inverse_class_name
,没有保存调用,没有特殊处理,但排除了自我跟踪。原因是,如果没有添加到关系语句中,mongoid 会自动使用
dependent: nullify
。并且使用 autosave: true 可以保存关系的更新(并且仅在关注时需要,因为我们不会直接更改关注者)。如果没有自动保存选项,您需要在方法中添加保存调用,因为 mongoid 不会自动保存关系更新(自 2.0.0.x 起)。我将 if 子句作为块,这样您就可以通过异常处理来更改它(
else raise FooException
)。.delete(user)
没问题,在 mongoid 文档中也提到过: http:// /mongoid.org/docs/relations/referenced/nn.html(向下滚动到“依赖行为”)。Following code worked fine for me (mongoid 2.3.x):
No
inverse_class_name
, no save calls, no special handling, but with exclusion of self-following.The reason is, that mongoid automatically uses
dependent: nullify
if not added to the relation statement. And withautosave: true
the update of relationships get saved (and is only needed for following, because we do not alter followers directly). Without autosave option you need to add a save call in the methods, because mongoid doesn't automatically save relationship updates (since 2.0.0.x).I put the if-clause as block, so you can alter it with exception handling (
else raise FooException
).The
.delete(user)
is okay, also mentioned in the mongoid docs: http://mongoid.org/docs/relations/referenced/n-n.html (scroll down to "DEPENDENT BEHAVIOUR").