开发者

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 ha开发者_如何学运维sh.

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


This syntax is capable with rails 4.

Message.includes(:user).find(1)


It is included in the SQL query. When you will call Message.find(1, :include => :user).user no query will be executed for that. All of the data is loaded in one SQL query.

Watch application log for evidence (tail -f log/development.log).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜