0

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.