Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can roll your <code>Tag.find</code> query into a single request to the DB, and add an appropriate where clause to limit the posts returned:</p> <pre><code>finder = Post.followed_by(@user) if params.has_key?(:tags) @tags = Tag.where(:content =&gt; params[:tags]) finder = finder.with_tags(@tags) end @allposts = finder.all </code></pre> <p><strong>in app/models/post.rb</strong></p> <pre><code>scope :with_tags, lambda { |tags| joins(:tags).group('posts.id').where(:tags =&gt; { :id =&gt; tags.map { |t| t.id } } ).having("COUNT(*) = ?", tags.length) } </code></pre> <p><strong>UPDATE</strong></p> <p>Here's what the with_tags scope does:</p> <ol> <li><code>joins(:tags)</code> Firstly we join the tags table to the posts table. Rails will do with with an inner join when you use the symbol syntax </li> <li><code>where(:tags =&gt; { :id =&gt; tags.map { |t| t.id } } )</code> We want to filter the tags to only find those tags provided. Since we are providing a list of tag objects we use map to generate an array of IDs. This array is then used in the where clause to create a <code>WHERE field IN (list)</code> query - the hash within a hash syntax is used to denote the table, then column within the table. </li> <li><code>group('posts.id')</code> So now that we have a list of posts with the requisite tags, however, if there are multiple tags we will have posts listed multiple times (once for each matched tag), so we group by the posts.id so that we only have 1 row returned for each post (it's also required to that we can do the count in step 4)</li> <li><code>having("count(*) = ?", tags.length)</code> This is the final piece of the puzzle. Now that we've grouped by the post, we can count the number of matched tags associated with this post. So long as duplicate tags are not allowed then if the number of matched tags (<code>count(*)</code>) is the same as the number of tags we were searching with (<code>tags.length</code>) Then we can be sure that the post has all the tags we were searching with.</li> </ol> <p>You can find a lot more information about the different query methods available for models by reading the <a href="http://guides.rubyonrails.org/active_record_querying.html" rel="nofollow">Active Record Query Interface Guide</a></p>
    singulars
    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.
 

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