2016-11-12 45 views
0

这里是我的用户和关系模型如何为current_user.following创建作用域?

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 

不过,我想这变成我的用户模型中的范围。

回答

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 
    

最后,您可以使用这些范围,因为你的期望:

# 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 
1

通过使用实例方法可以使一个方法对于用户模型

这样的:

class User < ActiveRecord::Base 

    def following? 
    self.following.present? 
    end 

end 

使用范围则只能拨打ActiveRecord的基于查询到模型的范围。

1

你也应该得到这样

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

,这应该在你的控制器来调用诸如

User.following?(current_user)