Rails: join with multiple conditions

前端 未结 3 579
遥遥无期
遥遥无期 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: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?

提交回复
热议问题