I have a model User which has_many :messages and Message which belong_to :user.
when I do Message.find(1, :include => :user) it doesn't return me user but if I do Message.find(1).to_json(:include => :user) it does include the user object in the hash.
How can I get it include it in Message.find(1, :include => :user) ?
This is a case of eager/lazy loading. When you do:
Message.find(1, :include => :user)
You are eagerly loading the user, becuase when you call @message.user, you aren't making another query to fetch the user, whereas doing:
Message.find(1)
Will find the message, and calling @message.user will make another SQL query(aka lazy loading).
If you look at the actual SQL queries getting sent to the server, you will see that you are infact fetching the user in the first example.
The reason why it isn't showing is because when you inspect @message it just shows the message, as opposed to calling to_json, which forces the inspection of user.
It is included, so if you call this:
@message = Message.find(1, :include => :user)
@message.user
Second query won't be executed because user is already loaded, while
@message = Message.find(1)
@message.user
will execute both queries
And useful screencast to understand what is going on
http://railscasts.com/episodes/22-eager-loading
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With