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)
기본적으로 내가 한 일은 이미 팔로우중인 사용자 목록을 얻었습니다. 그런 다음 사용자 테이블에서 ID가 이미 팔로우중인 사용자와 일치하지 않는지 확인합니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다