ed1t ed1t - 2 months ago 26
Ruby Question

rails 3 :include with find()

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) ?

Answer Source

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.