【发布时间】:2011-03-21 11:16:31
【问题描述】:
我有一个简单的模型,比如
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
【问题讨论】:
标签: ruby-on-rails-3 activerecord join