I have a simple model like
class Interest < ActiveRecord::Base has_and_belongs_to_many :user_profiles end class UserProfile < ActiveRecord::Base has_and_belongs_to_many :interests end
When I want to request all users with specific interests, this is a fairly simple implementation
UserProfile.joins(:interests).where('interests.id = ?', an_interest)
But how can I search for users who have several interests? Of course, if I do
UserProfile.joins(:interests).where('interests.id = ?', an_interest).where('interests.id = ?', another_interest)
I always get an empty result, because after the merge, no line can have both interest.id = an_interest and interest.id = another_interest.
Is there a way in ActiveRecord to express "I need a list of users who have 2 (specified) interests related?
update (solution) that the first working version I came up with is honored by Omar Kureshi
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
join activerecord ruby-on-rails-3
Filippo diotalevi
source share