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 played around a little with :include clauses, thinking that I
> should, at least, be able to fetch the record from the "lots" table
> and the "parts" table simultaneously (with something like a joins
> clause and a "lots.part_id = parts.id" WHERE clause), but didn't get
> anywhere with that.
:includes is useless here. :joins will do the trick.
>
> I will end up leaving this the way it is (most likely), especially
> since this isn't the right phase of development to be worrying about
> optimization, but I am curious how one might do this most efficiently.
>
> Is it most efficient to grab 1 record where record.id = blah and then
> all the (rest of the) records where record.id <> blah?
>
> Is it more efficient to grab all the records at once and write some
> ruby code to select the one record from the rest?
That's what I think I'd do.
> If so, what would
> that code look like? I don't like this:
>
> everything = Part.all
> the_one = everything.select {|x| x.id == 2}
> the_rest = everything.reject {|x| x.id != 2}
>
> That's going to iterate over all of the records. twice! in interpreted
> code!
So just iterate once, and test for the special value as you go. If you
can't do that, then make 2 DB queries.
>
> Any thoughts, ideas, or snide remarks?
>
> --wpd
Best,
--
Marnen Laibow-Koser
http://www.marnen.org
[email protected]
--
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 [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---