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

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -