Reputation: 4217
I'm unable to understand how to get all related records using associations instead of associated ids like user_id
and comment_id
.
Lets suppose I have three models User, Post, Comment, Image
and associations are
User
has_many :posts
has_many :comments
Post
belongs_to :user
has_many :comments
has_many :images
Comment
belongs_to :user
belongs_to :post
Image
belongs_to :post
Now I have an user_id
of user and finding user as:
@user = User.find_by_id(params[:id])
@comments = @user.comments
now I would like to fetch these comments with each of them a related record of their post. I want post hash instead of post_id
corresponding to every comment.
I want to do this in a single query.
If you have any idea, please suggest me.
Upvotes: 1
Views: 2029
Reputation: 11813
Use includes(:association)
:
@user = User.find_by_id(params[:id])
@comments = @user.comments.includes(:post)
NOTE: This would make another (second) query.
Alternatively, include it in your initial query:
@user = User.where(id: params[:id]).includes(comments: :post)
Upvotes: 3