aidiah aidiah - 6 months ago 11
Ruby Question

count with two where returns 0

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

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


However this is returning 0

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

log:

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

max max
Answer

Use the associations Luke!

class Post < ActiveRecord::Base
  has_many :replies
end

class Reply < ActiveRecord::Base
  belongs_to :post
end

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 %>