On Mon, Sep 28, 2009 at 6:07 PM, Marnen Laibow-Koser
<rails-mailing-l...@andreas-s.net> wrote:
> Patrick Doyle wrote:
>> I have the following:
>>
>> @lot = Lot.find(params[:id])
>>
>> part_nums = Part.all(:conditions => ["id <> ?", @lot.part.id])
>>
>> I guess I should mention that
>>
>> Lot :belongs_to => :part
>>
>> I was looking at the log following the execution of these two
>> statements and I saw something like this:
>>
>> Lot Load (0.4ms) SELECT * FROM "lots" WHERE ("lots"."id" = 13)
>> Part Load (0.3ms) SELECT * FROM "parts" WHERE ("parts"."id" = 2)
>> Part Load (0.9ms) SELECT * FROM "parts" WHERE (id <> 2)
>>
>> It looked a bit silly to me -- first I grab a record from the "parts"
>> table with an ID of 2, then I grab all the records from the parts
>> table whose ID is not 2.
>
> I think what's happening here is this: you're calling @lot.part.id, so
> Rails needs to load @lot.part, which accounts for the extra query.  To
> fix, use the :joins option on Lot.find, or simply call @lot.part_id.
>
I should let this be, but now I'm curious... what does :joins actually
do for me?

(in script/console)
>> l=Lot.find(13, :joins => :part)

produces (in the logfile)

SELECT "lots".* FROM "lots" INNER JOIN "parts" ON "parts".id =
"lots".part_id WHERE ("lots"."id" = 13)

and that looks like what I wanted.  But when I follow that up with

>> l.part

I see in the logfile:

SELECT * from "parts" WHERE ("parts"."id" = 2)

so it seems that the inner join was wasted.  Is this a development vs.
production thing?  (I know, I'm not supposed to worry about
optimization now, but I figure if I learn how to write generally more
optimal code by default, it will only help).

If I try:

>> l=Lot.find(13, :include => :part)

I see in the logfile:

SELECT * FROM "lots" WHERE ("lots"."id" = 13)
SELECT * FROM "parts" WHERE ("parts".id" = 2)

so neither the :joins nor the :include options seem to help, although
the :include option prevents the subsequent database access when I
finally access l.part

Again, this is not stopping me from anything, and I really should
leave the optimization phase for later, but I am curious about the
intended behavior of :include and :joins, and puzzled by the apparent
behavior.

--wpd

--~--~---------~--~----~------------~-------~--~----~
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+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to