views:

20

answers:

1

I have two models:

class Parent < ActiveRecord::Base
  has_many :children
end

class Child < ActiveRecord::Base
  belongs_to :parent
end

I want to find all parents AND their children, with conditions on the children only. BUT if the parent has no children that match that criteria, I still want the parent.

I tried this:

Parent.all(:include => :children, :conditions => {'children.some_condition' => 'some_value'})

However this doesn't return parents that have no matching children. I want ALL parents and only the children of those parents that match my condition.

Unfortunately I'm using Rails 2.1.1. I'd like to upgrade but it's not my major priority right now, so consider that a limitation in the possible implementation.
EDIT: Scratch that, just upgraded to 2.3.6, was fairly painless

Any help is greatly appreciated.

A: 

I'm not pretty sure if it will work with Rails 2.1.1, but I think it should.

Your condition is applied to all records - also for those that doesn't have any children. So you need to add additional condition like this:

Parent.all(:include => :children, :conditions => ["children.some_condition = ? OR children.id is null", "some_value"]
klew
just upgraded the service... it was actually quite easy, tests all passed... i'll try this tomorrow when i get the chance.
brad