Rails: join with multiple conditions

前端 未结 3 580
遥遥无期
遥遥无期 2020-12-30 12:54

I have a simple model like

class Interest < ActiveRecord::Base
  has_and_belongs_to_many :user_profiles
end

class UserProfile < ActiveRecord::Base
  h         


        
相关标签:
3条回答
  • 2020-12-30 13:28

    in (?) is no good - it's an OR like expression

    what you will need to do is have multiple joins written out 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
    

    You may need to change the main_join_clause to suit your needs.

    0 讨论(0)
  • 2020-12-30 13:35

    Try IN (?) and an array:

    UserProfile.joins(:interests).where('interests.id IN (?)', [1,2,3,4,5])
    
    0 讨论(0)
  • 2020-12-30 13:37

    This will get users that have at least one of the specified interests.

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

    To get users that have both of the specified interests I'd probably do something like this:

    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
    

    Not amazingly efficient, but it should do what you need?

    0 讨论(0)
提交回复
热议问题