Rails has_many :through with the where clause



我在Rails中构建了简单的Twitter应用程序。

现在我想to choose three random users that are not followed by the current user.

这是我的模型:

class User < ActiveRecord::Base
    has_many :tweets, dependent: :destroy
    has_many :followerships, class_name: 'Followership', foreign_key: 'followed_id'
    has_many :followedships, class_name: 'Followership', foreign_key: 'follower_id'
    has_many :followers, through: :followerships, source: :follower
    has_many :followed, through: :followedships, source: :followed
end
class Followership < ActiveRecord::Base
    belongs_to :follower, class_name: "User"
    belongs_to :followed, class_name: "User"
    validates :follower_id, presence: true
    validates :followed_id, presence: true
end
class Tweet < ActiveRecord::Base
  belongs_to :user
end

我尝试使用以下查询:

User.where.not(followers: current_user).order("RANDOM()").limit(3)

但它显然不起作用,因为我得到no such column: users.follower_id错误。

甚至有可能没有sql查询吗?

谢谢!

试试这个:

already_following = current_user.followed.map(&:id)
@users = User.where.not(id: already_following).order("RANDOM()").limit(3)

基本上,我所做的是获得已经被关注的用户列表。然后,检查 User 表中的 id 是否与已关注的用户不匹配。

相关内容

最新更新