创建跟踪/取消关注rails中其他模型的方法

时间:2015-03-30 17:54:40

标签: ruby-on-rails activerecord model associations jointable

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

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

我想做的是创建方法,允许用户:关注/取消关注名人,指明用户是否关注名人。同样在用户模型中,我想显示他们关注的名人列表,并在名人模型中显示跟随他们的用户。我试图对前两种方法这样做,但并不是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个实例的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

要验证用户是否只能关注名人,您可以为以下模型添加唯一验证,例如

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

不要忘记在数据库中添加uniq索引