Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I don't know if it will solve you problem but for complex queries like that I almost always just use <a href="https://github.com/ernie/squeel" rel="nofollow">Squeel</a>.</p> <p>Then do something like this:</p> <pre><code>@posts = Post.joins(:tags) .where{tags.name.like_any names_array} .group("post_id") .having("count(post_id) = #{names_array.size}") </code></pre> <p>The SQL hopefully looks something like this</p> <pre><code>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 </code></pre> <p>If I remember squeel is pretty good at using ILIKE instead of LIKE depending on the database used. (atleast better than AR)</p> <p>Also you could do this using AR without <a href="https://github.com/ernie/squeel" rel="nofollow">squeel</a> but I REALLY like some of the ideas and helpers that come with <a href="https://github.com/ernie/squeel" rel="nofollow">squeel</a> like <code>_all</code></p> <hr> <p>As for an explination...</p> <p>Assume I searched for TagsA and B.</p> <p>What that does is finds all the Posts with those tags.</p> <p>So you'll have something like:</p> <ul> <li>PostA TagA</li> <li>PostA TagB</li> <li>PostB TagA</li> <li>PostB TagB</li> <li>PostC TagA</li> </ul> <p>Then it will group all those different Post results by the joined tags using post_id.</p> <ul> <li>PostA TagA TagB</li> <li>PostB TagA TagB</li> <li>PostC TagA</li> </ul> <p>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.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload