【问题标题】:Rails: Getting the All Users Where User has not followed himRails:获取用户没有关注他的所有用户
【发布时间】:2016-07-03 02:20:08
【问题描述】:

我想列出所有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

谢谢

【问题讨论】:

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


    【解决方案1】:

    你可以通过以下方式来做

    先找到current_user关注的所有用户的id

    ids = current_user.followings.pluck(:id)
    

    然后找到除id之外的所有用户

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

    这可能对你有帮助

    【讨论】:

    • 嗨,谢谢 :) 它有效,我别无选择。不过我确实想提出一些建议。在 rails 4 我们可以使用 where not like this 。 User.where.not(id: ids) 。顺便谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-28
    • 1970-01-01
    • 1970-01-01
    • 2012-03-10
    • 1970-01-01
    • 1970-01-01
    • 2015-05-31
    相关资源
    最近更新 更多