Wants to get all parents with no children, etc

To all:

hi,

i have implemented the associations in my models

so i have a Parent model that has many Children model

but i need to get a list of Parents that do not have children
or
Parents that have just 2 children

or Parents that have children whose name is ‘James’, or ‘Sarah’, or
‘Betty’

or Parents whose children do not have names like ‘James’, or ‘Sarah’,
or ‘Betty’

I find it near impossible to use activerecord and the various find
methods.

Maybe I overlook something.

Please advise

Thank you.

On 2 Jan 2008, at 10:48, Kei Simone wrote:

or
Parents that have just 2 children

or Parents that have children whose name is ‘James’, or ‘Sarah’, or
‘Betty’

or Parents whose children do not have names like ‘James’, or ‘Sarah’,
or ‘Betty’

I find it near impossible to use activerecord and the various find
methods.

You’re right that activerecord won’t help you much with this sort of
stuff - you will be writing out a bunch of joins yourself (with the
exception of ‘parents with 2 children’: you can use a counter_cache,
at which point it becomes trivial).
To get all parents with no children, you need to be generating sql of
the form

select parents.* from parents
left outer join children on children.parent_id = parents.id
where children.id IS NULL

if you want parents whose children match some condition

select parents.* from parents
inner join children on children.parent_id = parents.id
where

if you want parents with no children matching some condition

select parents.* from parents
left outer join children on children.parent_id = parents.id AND
where children.id IS NULL

You can tell activerecord what joins to apply with the :joins option

Fred