follow/unfollow rails 中其他模型的创建方法

Creating methods that follow/unfollow other models in rails

我有一个关系设置,一个用户可以关注多个名人。

class User < ActiveRecord::Base
  has_many :followings, :dependent => :destroy
  has_many :celebrities, :through => :following
end

class Following < ActiveRecord::Base
  belongs_to :user
  belongs_to :celebrity
end

class Celebrity < ActiveRecord::Base
  has_many :followings, :dependent => :destroy
  has_many :users, :through => :following
end

我想做的是创建允许用户执行以下操作的方法:follow/unfollow名人,表明用户是否关注名人。同样在用户模型中,我想显示他们关注的名人列表,并在名人模型中显示关注他们的用户。我已经尝试对前两种方法这样做,但不是 100% 确定如何编写其余的方法。

class User < ActiveRecord::Base
  ...
  def follow(celebrity)
    followings.create(celebrity_id: celebrity.id)
  end

  def unfollow(celebrity)
    followings.find_by(celebrity_id: celebrity.id).destroy
  end

  def following?(celebrity)
  end

  def follows
  end
end

class Celebrity < ActiveRecord::Base
  def followers
  end
end

我的方向正确吗?此外,确保用户只能关注名人 一次 以防止创建额外的 followings 实例的最佳方法是什么?

要验证用户只能关注一个名人,您可以在关注模型中添加唯一验证,例如

class Following < ActiveRecord::Base
  belongs_to :user
  belongs_to :celebrity

  validates :celebrity_id, uniqueness: { scope: :user_id }
end


class User < ActiveRecord::Base
  has_many :followings
  has_many :celebrities, through: :followings

  def follow(celebrity)
    followings.create(celebrity_id: celebrity.id)
  end

  def unfollow(celebrity)
    followings.find_by(celebrity_id: celebrity.id).destroy
  end

  def following?(celebrity)
    celebrity.followers.find_by(id: id).present?
  end

  def follows
    celebrities
  end
end

class Celebrity < ActiveRecord::Base
  has_many :followings
  has_many :users, through: :followings

  def followers
    users
  end
end

并且不要忘记在数据库中添加唯一索引