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
Ok so I found no way to avoid a find_by_sql. Here is what I've done.
@posts = Post.find_by_sql([ "SELECT * FROM posts p
JOIN (
SELECT pt.post_id FROM posts_tags pt
JOIN posts p ON p.id = pt.post_id
JOIN tags t ON t.id = pt.tag_id
WHERE t.label IN (?)
GROUP BY pt.post_id
HAVING count(pt.post_id) = ?
) ct ON c.id = ct.post_id", names_array, names_array.size])
I personally don't completely understand this query (found on http://www.sergiy.ca/how-to-write-many-to-many-search-queries-in-mysql-and-hibernate/ - #3). Especially the part where it joins a select. So if anyone could explain how really work this query it would be great.
Further more, if anyone knows how to do this in a more "rails" way (than a hard coded query), I'd love it.
Hope this helps some people.