2011-03-21 110 views
8

当我想查询所有与特定兴趣的用户我有一个像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 

回答

4

是没有好 - 这是一个或类似表达

,你需要做的是有多个联接写出longhanded

(?)
profiles = UserProfile 
interest_ids.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 interests_#{idx} on 
         (#{main_join_clause} and interests_#{idx}.id = ?)", i] 
    profiles = profiles.join(join_clause) 
end 
profiles 

您可能需要更改main_join_clause以满足您的需求。

+0

这是更复杂,我希望:)!但你绝对指出我正确的方向。谢谢。唯一的区别是我不得不像你写的那样“内部加入interest_user_profiles”而不是“内部加入兴趣”。 – 2011-03-21 12:40:28

+0

...并用'interest _#{idx} .interest_id =?' – 2011-03-21 12:42:51

+0

替换'interest _#{idx} .id =?'是啊 - 这是M-to-M连接吗?这将是有道理的,对不起,没有读过这一点! :d – 2011-03-21 16:47:57

2

这将让一个有特定兴趣的至少一个用户。

UserProfile.joins(:interests).where(:id => [an_interest_id, another_interest_id]) 

戈同时具有特定利益的牛逼用户我可能会做这样的事情:

def self.all_with_interests(interest_1, interest_2) 
    users_1 = UserProfile.where("interests.id = ?", interest_1.id) 
    users_2 = UserProfile.where("interests.id = ?", interest_2.id) 

    users_1 & users_2 
end 

不惊人的效率,但它应该做的,你需要什么?

+0

我试过'UserProfile.joins(:interests).where(“interests.id =?”,[25,26])'但它没有工作 – 2011-03-21 11:34:49

+0

不,它仍然不起作用。我在查询'SELECT“user_profiles *中得到语法错误。* FROM”user_profiles“INNER JOIN”interests_user_profiles“ON”interests_user_profiles“。”user_profile_id“=”user_profiles“。”id“INNER JOIN”兴趣“ON”兴趣“。 “id”=“interest_user_profiles”。“interest_id”WHERE(interests.id = 25,26)' – 2011-03-21 12:15:13

+0

我刚刚读过你对另一个答案的评论 - 我没有意识到你需要一个合乎逻辑的AND。我的答案会做一个OR。 – Ant 2011-03-21 12:18:23

0

尝试IN (?)和数组:

UserProfile.joins(:interests).where('interests.id IN (?)', [1,2,3,4,5]) 
+1

IN子句使逻辑或(有一个兴趣或其他或两者)...我需要一个逻辑与(具有所有兴趣) – 2011-03-21 12:13:43