aidiah aidiah - 2 years ago 60
Ruby Question

count with two where returns 0

I'm trying to count all replies with an image using:

<%= Reply.where(:post_id => => true).count %>

However this is returning 0

How can I properly count the number of replies that contain an image?


SELECT COUNT(*) FROM "replies" WHERE "replies"."post_id" = 1 AND "replies"."reply_file_fingerprint" = 't'

max max
Answer Source

Use the associations Luke!

class Post < ActiveRecord::Base
  has_many :replies

class Reply < ActiveRecord::Base
  belongs_to :post

This will let us do:

post.replies.where(reply_file_fingerprint: true).count

However this will cause what is known as N+1 query since each post will cause a COUNT query on the replies table.

Instead you may want load it ahead of time with

@posts = Post.eager_load(:replies)
             .where(replies: { reply_file_fingerprint: true })

And instead of .count use the smarter .size:

<% @posts.each do |post| %>
  <%= post.replies.size %>
<% end %>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download