2014-01-16 138 views
1

我在Rails中構建了一個簡單的Twitter應用程序。我想to choose three random users that are not followed by the current userRails has_many:通過where子句

這裏是我的模型:

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查詢?

謝謝!

回答

2

試試這個:

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

基本上我做什麼,是已經得到了遵循用戶的列表。然後,您檢查用戶表的id是否與已經遵循的用戶匹配。

+1

這工作!非常感謝@安德魯! –