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 do this kind of thing :
Post.joins(:tags).where('tags.name ILIKE ?', var)
But instead of having just one var, I’d like to use an array.
I tried :
Post.joins(:tags).where('tags.name IN (?)', names_array)
But unfortunately it does a simple LIKE (not ILIKE) and works like a OR condition which sounds perfectly logical.
I also found another solution by using find_by_sql in this post
http://snippets.dzone.com/posts/show/32
But it seems a bit ugly to me.
To better understand the problem.
I’ve got 3 posts :
PostA
PostB
PostC
PostA is related to TagA TagB and TagC tags.
PostB is related to TagA and TagB tags.
PostC is only related to TagA.
If I look for TagA and TagC Posts I’d like to finds PostA because it is related to both Tags.
Using a hash condition returns PostA PostB and PostC.
What I want is the Posts which are related to “at least” all the specified Tags.
So anyone has a better way to handle this ?
Thanks.
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:
The SQL hopefully looks something like this
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
_allAs 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.