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:
You are eagerly loading the user, becuase when you call
@message.user, you aren’t making another query to fetch the user, whereas doing:Will find the message, and calling
@message.userwill 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
@messageit just shows the message, as opposed to callingto_json, which forces the inspection ofuser.