如何为current_user.following创建一个范围?

时间:2016-11-12 01:10:01

标签: ruby-on-rails

以下是我的用户和关系模型

class User < ActiveRecord::Base
  has_many :active_relationships, class_name:  "Relationship",
                                foreign_key: "follower_id",
                                dependent:   :destroy
  has_many :passive_relationships, class_name:  "Relationship",
                                foreign_key: "followed_id",
                                dependent:   :destroy
  has_many :followers, through: passive_relationships, source: :follower
  has_many :following, through: :active_relationships, source: :followed

class Relationship < ActiveRecord::Base
  belongs_to :follower, class_name: "User", counter_cache: :followeds_count
  belongs_to :followed, class_name: "User", counter_cache: :followers_count
  validates :follower_id, presence: true
  validates :followed_id, presence: true
  validates :followed, uniqueness: { scope: [:follower, :followed] }
end

在用户控制器中,我可以这样做:

@users = current_user.following

但是我想把它变成我的用户模型中的范围。

3 个答案:

答案 0 :(得分:1)

通过使用实例方法,您可以为用户模型

创建一个方法 像这样:

 class User < ActiveRecord::Base

  def following?
   self.following.present?
  end

 end

通过使用Scope,您只能将基于activerecord的查询调用到模型范围内。

答案 1 :(得分:1)

你也应该这样做

scope :following?, lambda { |user|
    {  user.following.present?    }

这应该像你的控制器一样调用

User.following?(current_user) 

答案 2 :(得分:1)

您可以采取两种措施:

  1. 查找关注某人的所有用户

    class User < ActiveRecord::Base
      scope :following_to, -> (user_id) {
        where(
          "id IN ( SELECT followed_id 
                   FROM relationships
                   WHERE follower_id = ?
                 )",
          user_id
        )
      }
    end
    
  2. 查找关注任何人的所有用户,这意味着他们是关注者

    class User < ActiveRecord::Base
      scope :follower, -> {
        where("id IN ( SELECT followed_id FROM relationships)")
      }
    end
    
  3. 最后,您可以将这些范围用作您的期望:

    # Find all users who are following to User (id = 1)
    User.following_to(1)
    
    # Find all users who are following someone, 
    # aka they are a follower
    User.follower