comment count with attachment. Use a condition to test whether a record has an active archive attachment

28 Views Asked by At

I'm learning binaries, I have a problem that I've been going crazy about for several days, I created an application with a 2 tables: post and a child table of comments, in the comments table I have an attached field has_one_attached with active_storage. I would like to count only the comments that have an attachment and show the count in the Post table displayed on the post index page something like this:

this is what I would like to achieve

# models
class Comment< ApplicationRecord
belongs_to :Post
has_one_attached :image

in the comment view I can successfully use the following condition

# show comment
<% if comment.image.attached? %>

 <%end%>

but I can't get this condition to work in the index view of Post I wrote something like this

<% if post.comment.image.attached? %>

 <%end%>

where am I wrong

1

There are 1 best solutions below

0
Luigi On

well after so many days I had to write my first question about stack_overflow to find the solution, and it's also trivial the post maybe it can be useful to others

All I had to do was insert this into my index table:

<%= post.comments.joins(:image_attachment).count %>

I was missing the convention that uses active_storage or adding _attachment to my image field

:image_attachment

this post helped me understand

and everything works now