Reputation: 634
I'm currently working with Rails 5 and Postgresql. There's a model Post that can have many comments, through a model called PostComments, that way a comment can belong to a single post, but that post can have many comments. I'm trying to get all comments, grouped in the ones belonging to a specific user, and all other that not.
class Post < ApplicationRecord
has_many :post_comments
has_many :comments, through: :post_comments
...
class Coment < ApplicationRecord
has_many :post_comments
has_many :posts, through: :post_comments
...
Currently I'm doing two queries and comparing, like:
foo = Comment.select(:id, :description)
bar = Comment.joins(:post).select(:id, :description).where(posts: { id: post_id })
remaining_comments = [foo - bar, foo]
This gives me all comments for a specific store, and all the remaining ones, but I was wondering is there a better way on doing this?
Upvotes: 0
Views: 191
Reputation: 2624
You can get the comments in one query like below:
@comments = Comment.left_outer_joins(:post)
.select("comments.id,comments.description,posts.id as post_id")
.where("posts.id = ? OR posts.id IS NULL", post_id })
Then split using group_by
:
remaining_comments = @comments.group_by(&:post_id)
Upvotes: 2
Reputation: 103
If I'm interpreting you correctly, you're trying to efficiently get an array of PostComments that do not belong to a particular Post?
If this is the case, simply use the not
method:
x = # given Post id
post = Post.find(x).id
postcomments = PostComment.where.not(post_id: post)
Upvotes: 1