HABTM mongoid 关注者/关注者

2023-11-29

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 2.3.x):

class User
  include Mongoid::Document

  field :name, type: String

  has_and_belongs_to_many :following, class_name: 'User', inverse_of: :followers, autosave: true
  has_and_belongs_to_many :followers, class_name: 'User', inverse_of: :following

  def follow!(user)
    if self.id != user.id && !self.following.include?(user)
      self.following << user
    end
  end

  def unfollow!(user)
    self.following.delete(user)
  end
end

No inverse_class_name,没有保存调用,没有特殊处理,但排除自我跟随。

原因是,mongoid 自动使用dependent: nullify如果没有添加到关系语句中。与autosave: true关系的更新被保存(并且仅在关注时需要,因为我们不直接改变关注者)。如果没有自动保存选项,您需要在方法中添加保存调用,因为 mongoid 不会自动保存关系更新(自 2.0.0.x 起)。

我将 if 子句作为块,因此您可以通过异常处理来更改它(else raise FooException).

The .delete(user)没问题,mongoid 文档中也提到了:http://mongoid.org/docs/relations/referenced/n-n.html(向下滚动到“相关行为”)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

HABTM mongoid 关注者/关注者 的相关文章

随机推荐