Note that there are some explanatory texts on larger screens.

plurals
  1. POhow to query a limited set of records with ActiveRecord
    text
    copied!<p>This has been driving me crazy for the last couple of hours as I'm sure there must be a simple solution. Let's say I have the following models:</p> <pre><code>class Post &lt; ActiveRecord::Base has_many :comments end class Comment &lt; ActiveRecord::Base belongs_to :post end </code></pre> <p>And the Comment model has an attribute called Flagged. Assume the post has ten comments and the first two and last two have been marked as flagged. </p> <p>I want to get a count of how many of the first 5 comments of a post have been flagged. In this case I would want to return 2. So at first I tried:</p> <pre><code>post.comments.limit(5).where(comments: { flagged: true }).count </code></pre> <p>But this returns 4 which makes sense because it's finding the first 5 records where flagged is true. My question is, how can I do the count on only the limited resultset? I tried:</p> <pre><code>first_five_comments = post.comments.limit(5) first_five_comments.where(flagged: true).count </code></pre> <p>This also returns 4 as it's just chaining the relations together and executing the same query as above.</p> <p>I know I could do this with a straight SQL statement, but it just seems like there should be a more Rails way to do it. Do I have to add a .all to the above statement and then do the count within the returned array? Obviously this doesn't work:</p> <pre><code>first_five_comments = post.comments.limit(5).all first_five_comments.where(flagged: true).count </code></pre> <p>because I can't use "where" on an array. If I do have to do it like this, how would I search within the array the get the count?</p> <p>Any help is appreciated!</p>
 

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