Search code examples
ruby-on-railsrails-activerecordto-json

Serialize to json rails models with associated records


Suppose I have Folder with has_many association to File.

I had a small action where I rendered json like this

render json: folder.to_json(include: :files)

I've tried to render a bit more complicated json response with following

render json: {status: 'ok', main_folder: folder}

but this obviously doesn't include associated records. How can I include them?

P.S. I would like not to use views in this application and not to override to_json method (as I want to render in another action complicated json with Folder records, but without associated Files) in models if it is possible.

EDIT I've managed to find a workaround for the problem, but it looks ugly

intermediate_obj = folder.attributes.merge(files: folder.files)
render json: {status: 'ok', main_folder: intermediate_obj}

Solution

  • You can do something like:

    render json: {status: 'ok', main_folder: folder.as_json(include: :files}