Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 842
ed1t Avatar asked Apr 06 '26 17:04

ed1t


2 Answers

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.

like image 58
Mike Lewis Avatar answered Apr 09 '26 11:04

Mike Lewis


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

like image 44
fl00r Avatar answered Apr 09 '26 11:04

fl00r



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!