0

I have a model find like this for an API:

Article.includes(:comments).all

When applying the to_json method, I'd like to get back the article along with an array of the comments. Unfortunately, the to_json method only returns the Article model. Help.

Robert Ross
  • 1,895
  • 2
  • 23
  • 32

1 Answers1

8

use this :

Article.includes(:comments).find(your_article_id).to_json(:include => :comments)

using all on the model will fetch every single article available in the database. using to_json on a relation should get you a json array of all records returned by the relation as json.

you can get additional info here.

m_x
  • 12,357
  • 7
  • 46
  • 60
  • 1
    Hope this is helpful for anyone else coming here looking for the answer, if you're using Rails to respond with JSON and want to include an association, there's another answer here: http://stackoverflow.com/questions/17730121/include-associated-model-when-rendering-json-in-rails – hummmingbear Mar 23 '15 at 10:05