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 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.
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? 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!
Any thoughts, ideas, or snide remarks?
–wpd