ruby on rails - Get all related records using associations -
i'm unable understand how related records using associations instead of associated ids user_id
, comment_id
. lets suppose have 3 models user, post, comment, image
, associations
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 have user_id
of user , finding user as:
@user = user.find_by_id(params[:id]) @comments = @user.comments
now fetch these comments each of them related record of post. want post hash instead of post_id
corresponding every comment. want in single query. if have idea, please suggest me.
use includes(:association)
:
@user = user.find_by_id(params[:id]) @comments = @user.comments.includes(:post)
note: make (second) query.
alternatively, include in initial query:
@user = user.where(id: params[:id]).includes(comments: :post)
Comments
Post a Comment