Yea this is one of those exceptions where it's better to leverage the
DB (1 query) than pull in all 900 records and parse each one (900
queries / linear time algorithm) i.e. you shouldnt be afraid of
find_by_sql when it really is appropriate. What youre trying to do is
a very basic SQL JOIN operation:

(in the child model - children with *no lunchboxes)
SELECT * from lunchboxes
  LEFT JOIN children ON children.id = lunchboxes.id
  WHERE lunchboxes.id IS NULL

(would give you all children *with lunchboxes)
SELECT * from lunchboxes
  INNER JOIN children ON children.id = lunchboxes.id

You need to think in terms of 'Sets' when it comes to DB, i.e. DB's
are not the procedural things that languages are, you generally work
in terms a set or subset and not individual records.

Also I just did the above SQL off the top of my head - you should
probably test it first..

brez


On Fri, Nov 21, 2008 at 11:15 AM, Glenn Little <[EMAIL PROTECTED]> wrote:
>
> Suppose I have the following models:
>
> Parent
>  (#has_many :children, but I don't want to expose this association
>  directly.)
>
> Child
>  belongs_to :parent
>  has_one    :lunchbox
>
> Lunchbox
>  belongs_to :parent
>  belongs_to :child
>
>
> I want to put a has_many in the parent to give me all the
> children that do not have a Batman lunchbox (or who have
> no lunchbox at all).  Basically, in railsy pseudo code it
> would be something in the parent model like:
>
>  list = []
>  for each of my children do |c|
>   if (c.lunchbox.nil?) || (c.lunchbox.batman == false)
>     list << c
>   end
>  end
>  return c
>
> I'd like to put this in a has_many instead, but I'm stuck
> on figuring out the :conditions and :include options that
> I need to make the above happen.
>
> I'm thinking there is some magic with hashes and/or arrays in
> an :include option to the has_many declaration, but frankly I'm
> pretty weak at this point regarding those complex :include
> specs and how they play out, and so far have been unable to get
> it working.  I think the "all the children that do *not* have
> a lunchbox" part is what's tripping me up.
>
> Thanks for any pointers!
>
>        -glenn
>
> >
>

--~--~---------~--~----~------------~-------~--~----~
SD Ruby mailing list
[email protected]
http://groups.google.com/group/sdruby
-~----------~----~----~----~------~----~------~--~---

Reply via email to