Rails:获取用户没有关注他的所有用户

时间:2016-07-02 15:54:51

标签: ruby-on-rails ruby-on-rails-4 activerecord

我想列出current_user未关注的所有用户,以便current_user可以关注他

用户模型如下所示:

class User < ActiveRecord::Base
  has_many :follower_relationships, foreign_key: :following_id, class_name: 'Follow'
  has_many :followers, through: :follower_relationships, source: :follower
  has_many :following_relationships, foreign_key: :follower_id, class_name: 'Follow'
  has_many :following, through: :following_relationships, source: :following
end

Follow类看起来像这样。

class Follow < ActiveRecord::Base  
  belongs_to :follower, foreign_key: 'follower_id', class_name: 'User'
  belongs_to :following, foreign_key: 'following_id', class_name: 'User'
end  

我知道我可以得到以下所有内容:

current_user.following

我希望获得current_user未关注的所有用户。 我试着这样做,但我做不到:(

User.all.where.not(following: current_user.following)

如果您不能正确理解问题,我会尝试举例说明。

假设有用户A , B , C , D ,E。可以说A跟随BC。我想显示DE,以便A知道他没有关注DE

由于

1 个答案:

答案 0 :(得分:0)

你可以通过以下方式来实现

首先查找current_user正在关注的所有用户的ID

ids = current_user.followings.pluck(:id)

然后查找除该ID之外的所有用户

users = User.where("id NOT IN ?", ids)

这可能会对你有所帮助