Ethan Mick
Ethan Mick

Reputation: 9567

How can I make associations loaded in rails 3 in JSON?

In my rails 3.1 application, I have Lists, which have many tasks. All the associations are setup appropriately, I can call aList.tasks, to and I can see the tasks for the List. However, when I load /lists.json, I get the following output:

{
created_at: "2011-12-07T21:51:31Z",
id: 1,
title: "Test 1",
updated_at: "2011-12-07T21:51:31Z"
}

So, the List is serialized to JSON, but its "task" associations are not (tasks are nested under lists, so /list/1/tasks would get the tasks... but just for that 1 list). And if I have 500 lists, I don't want to have to call 500 times to get all the tasks for each list - I want to get all the tasks when I get all the lists. How can I set this up so the JSON also includes the association? Thoughts?

Thank you!

Upvotes: 1

Views: 1126

Answers (1)

Max Chernyak
Max Chernyak

Reputation: 37367

When rendering a list simply add include: :tasks into to_json.

format.json do
  render json: @list.to_json(include: :tasks)
end

P.S. Don't forget that the new hash syntax only works for ruby >=1.9.2. Here's the old syntax.

format.json do
  render :json => @list.to_json(:include => :tasks)
end

Upvotes: 6

Related Questions