Wednesday, September 28, 2011

[Rails] Re: newbie trying to understand include

ERB wrote in post #1024149:
> this works for me:
> @user = User.where(:id => params[:id] ).joins('LEFT JOIN companies
> ON companies.id = users.company_id')
>
> so then I guess its a question on understanding eager loading?

Think carefully about what you're trying to solve here. Eager loading is
intended to prevent the n+1 query problem.

In the case you show here your eager loading would actually cause more
queries than not using eager loading at all. You are trying to find a
single user (1 SQL query), then you're trying to ask for eager loading
(1+1 SQL queries). Not only have you not saved yourself anything, you
actually reduced performance.

By fetching only one user object you might as well wait until some
information for the associated companies are actually needed before
hitting the database.

Take a look at the first example in the section on Eager Loading that
you'll find a little less than half way down on the following page:

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

There is a very clear explanation of what eager loading is, and how it
should be used.

--
Posted via http://www.ruby-forum.com/.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate