当我想查询所有与特定兴趣的用户我有一个像Rails的:与多个条件
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(指定)的利益关联?
更新(解决方案)这就是我来到了第一个工作版本,荣誉给奥马尔的用户列表库雷希
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
这是更复杂,我希望:)!但你绝对指出我正确的方向。谢谢。唯一的区别是我不得不像你写的那样“内部加入interest_user_profiles”而不是“内部加入兴趣”。 – 2011-03-21 12:40:28
...并用'interest _#{idx} .interest_id =?' – 2011-03-21 12:42:51
替换'interest _#{idx} .id =?'是啊 - 这是M-to-M连接吗?这将是有道理的,对不起,没有读过这一点! :d – 2011-03-21 16:47:57