HABTM蒙古型追随者/追随者 [英] HABTM mongoid following/follower

查看:90
本文介绍了HABTM蒙古型追随者/追随者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Mongoid在habtm上附带.push,这会在两个方向上设置habtm关系.尽管delete将#delete删除关联的记录,但是没有记录的方法可以仅删除我所见过的关系.有更好的方法吗?

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

推荐答案

以下代码对我来说效果很好(mongoid 2.3.x):

Following code worked fine for me (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

没有inverse_class_name,没有保存调用,没有特殊处理,但是不包括自我跟踪.

No inverse_class_name, no save calls, no special handling, but with exclusion of self-following.

原因是,如果未添加到关系语句中,则蒙古语会自动使用dependent: nullify.使用autosave: true可以保存关系的更新(并且仅需要关注,因为我们不会直接更改关注者).如果没有自动保存选项,则需要在方法中添加一个保存调用,因为mongoid不会自动保存关系更新(自2.0.0.x开始).

The reason is, that mongoid automatically uses dependent: nullify if not added to the relation statement. And with autosave: 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).

我将if子句放在了块中,因此您可以使用异常处理(else raise FooException)对其进行更改.

I put the if-clause as block, so you can alter it with exception handling (else raise FooException).

.delete(user)还可以,在mongoid文档中也提到过: http://mongoid.org/docs /relations/referenced/nn.html (向下滚动到依赖行为").

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").

这篇关于HABTM蒙古型追随者/追随者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆