Reputation: 25
I am trying to join tables in posts model id matching with comment id in comments model.comment model is belonging to post model. my active record query in controller is:
Post.joins(:comments)
It generate query like this
SELECT "posts".* FROM "posts" INNER JOIN "comments" ON "comments"."post_id" = "post"."id"
but I am not able to select comments.How can I generate a query like below
SELECT * FROM "posts" INNER JOIN "comments" ON "comments"."post_id" = "post"."id"
Upvotes: 0
Views: 430
Reputation: 6773
If you want to retrieve the comments data along with posts, you should use .includes
instead of .joins
.
Post.includes(:comments)
Naturally the above will return some posts and you can get to their comments through their relation without another hit to the database.
There's a nice article about includes vs joins here.
Upvotes: 1