I have a Post
model that has many comments
class Post < ApplicationRecord
has_many :comments
end
How do I get distinct posts that have comments excluding the posts that do not have comments?
I believe that Post.joins(:comments).distinct("posts.*")
does the job.
Is there any better alternative?
I emphasize that the result should not have duplicate entries of posts, which is what happens when we join with comments (one-to-many relationship).
Looking at this again, and considering Mark's comment to my original solution, the simplest solution may just be to drop the "posts.*"
from your original.
Post.joins(:comments).distinct
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments