Skip to content Skip to sidebar Skip to footer

Rails: Has Many Through Associations -- Find With And Condition, Not Or Condition

I have the following query method in my ActiveRecord model: def self.tagged_with( string ) array = string.split(',').map{ |s| s.lstrip } select('distinct photos.*').joins(:

Solution 1:

This should work:

def self.tagged_with( string )
  array = string.split(',').map{ |s| s.lstrip }select('distinct photos.*').
    joins(:tags).
    where('tags.name' => array).group("photos.id").
    having("count(*) = #{array.size}")
end

Above will match photos that have tags red and blue at least. So that means if a photo has red, blue and green tags, that photo would match too.

Solution 2:

You could change your select statement to the following:

select('distinct photos.*').joins(:tags).where('tags.name = ?',  array.join(' OR '))

Which will properly create the OR string in the where clause.

ian.

Solution 3:

LOL the solution for this is not a simple task--I thought through it from a SQL standpoint and it was UGLY. I figured somebody else has to have tried this so I did some searching and found this post that should help you:

HABTM finds with "AND" joins, NOT "OR"

Post a Comment for "Rails: Has Many Through Associations -- Find With And Condition, Not Or Condition"