Reputation: 22515
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
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
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