sql - Rails: Has many through associations -- find with AND condition, not OR condition -
i have following query method in activerecord model:
def self.tagged_with( string ) array = string.split(',').map{ |s| s.lstrip } select('distinct photos.*').joins(:tags).where('tags.name' => array ) end
so, finds records have tags taken comma separated list , converted array.
currently matches records matching tags -- how can make work matches tags.
ie: if if input: "blue, red" records tagged blue or red.
i want match records tagged blue , red.
suggestions?
-- edit --
my models so:
class photo < activerecord::base ... has_many :taggings, :dependent => :destroy has_many :tags, :through => :taggings ... def self.tagged_with( string ) array = string.split(',').map{ |s| s.lstrip } select('distinct photos.*').joins(:tags).where('tags.name' => array ) end ... end class tag < activerecord::base has_many :taggings, :dependent => :destroy has_many :photos, :through => :taggings end class tagging < activerecord::base belongs_to :photo belongs_to :tag end
a tag has 2 attributes: id , name (string).
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 match photos have tags red , blue at least. means if photo has red, blue and green tags, photo match too.
Comments
Post a Comment