class Interest < ActiveRecord::Base
has_and_belongs_to_many :user_profiles
end
class UserProfile < ActiveRecord::Base
has_and_belongs_to_many :interests
end
와 같은 간단한 모델이 있습니다. 특정 관심사를 가진 모든 사용자를 쿼리하려면 상당히 간단합니다.
UserProfile.joins(:interests).where('interests.id = ?', an_interest)
그러나 여러 관심사를 가진 사용자를 어떻게 찾을 수 있습니까? 물론
UserProfile.joins(:interests).where('interests.id = ?', an_interest).where('interests.id = ?', another_interest)
조인 후에 아무런 행도 동시에 interest.id = an_interest 및 interest.id = another_interest를 가질 수 있기 때문에 항상 빈 결과를 얻습니다.
ActiveRecord에서 "2 개의 (지정된) 관심사를 가진 사용자 목록을 원하십니까?"라는 첫 번째 작업 버전 인
업데이트 (솔루션) Omar Qureshi
specified_interests.each_with_index do |i, idx|
main_join_clause = "interests_#{idx}.user_profile_id = user_profiles.id"
join_clause = sanitize_sql_array ["inner join interests_user_profiles interests_#{idx} on
(#{main_join_clause} and interests_#{idx}.interest_id = ?)", i]
relation = relation.joins(join_clause)
end
그건 내가 바라는 것보다 더 복잡합니다 :)! 그러나 당신은 분명히 나를 올바른 방향으로 가리켰다. 감사. 유일한 차이점은 당신이 쓴 것처럼'inner join interests'보다는'inner join interests_user_profiles'입니다. –
... '관심사 _ # {idx} .id =?'를'관심 _ # {idx} .interest_id =? '로 대체하십시오. –
아 - M 대 M 가입 이었습니까? 그것은 의미가있을 것입니다, 죄송합니다 그 비트를 읽지 못했습니다! :디 –