ruby on rails - How to get model with relation as hash? -
i want hash representation of post
model posts's related comments included array of hashes.
my models:
class post < activerecord::base has_many :comments end class comment < activerecord::base belongs_to :post end
so output should this:
{ "id": 3, "body": "this post", "comments": [ { "id": 1, "post_id": 3, "body": "this comment", } ] }
things have tried (that return post, not related comments:
post.includes(:comments).as_json post.eager_load(:comments).as_json
you can try following:
post.as_json(include: :comments)
Comments
Post a Comment