I\'m trying to do a simple Post/Tags relation in rails 3. Everything working fine except when I want to query the Posts which are related to several tags. Basically I\'d like to
I don't know if it will solve you problem but for complex queries like that I almost always just use Squeel.
Then do something like this:
@posts = Post.joins(:tags)
.where{tags.name.like_any names_array}
.group("post_id")
.having("count(post_id) = #{names_array.size}")
The SQL hopefully looks something like this
SELECT "posts".* FROM "posts"
INNER JOIN "tags" ON "tags"."post_id" = "posts"."id"
WHERE (("tags"."name" LIKE "TagA" OR "tags"."name" LIKE "TagB"))
GROUP BY post_id
HAVING count(post_id) = 2
If I remember squeel is pretty good at using ILIKE instead of LIKE depending on the database used. (atleast better than AR)
Also you could do this using AR without squeel but I REALLY like some of the ideas and helpers that come with squeel like _all
As for an explination...
Assume I searched for TagsA and B.
What that does is finds all the Posts with those tags.
So you'll have something like:
Then it will group all those different Post results by the joined tags using post_id.
Then it will check the number of Tags the SQL line has by checking how many forgien_ids are present. Since A and B have 2 tags you know it matched all you input.