Henley Wing Chiu
Henley Wing Chiu

Reputation: 22515

Rails includes with eager loading => nested models not in to_json version?

I have a class TwitterUser that has many TwitterLists

class TwitterUser < ActiveRecord::Base    
    has_many :twitter_lists, :dependent => :destroy
end

When I do:

user = TwitterUser.includes(:twitter_lists).find(12615489)

then:

lists = user.twitter_lists

it eagerly loads the twitter lists for that user in the first "find", so it doesn't run a query when I do user.twitter_lists (this is expected).

However when I try to convert the user to JSON like: user.to_json

I don't see the nested association "twitter_lists" anywhere in the JSON. Even though I used eager loading. Why is this? And how can I make it appear in the JSON?

Upvotes: 0

Views: 609

Answers (2)

Frederick Cheung
Frederick Cheung

Reputation: 84114

To include the association in the output of to_json you need to pass :include => :twitter_lists to to_json

There is no connection between the associations that are eager loaded and the associations that are included in the output of to_json - the two are completely independant.

Upvotes: 1

shishirmk
shishirmk

Reputation: 425

Check this answer May be this is what you need

Rails find method - select columns from ":include" table parameter

includes is just for eager loading. Which means it is cached somewhere but not actually returned

Upvotes: 0

Related Questions