views:

119

answers:

1

Given the following scenario, using activerecord:

User belongs_to Event

I want to find all the Users who do not have an Event with the name "party".

So I tried the following:

User.all(:joins => :event, :conditions => ["events.name != ?", "party"])

However, that will only return those Users who do have an event, but just not a "party" event. It won't return all the Users who have no event at all, because :joins automatically limits the results to associated records only.

I could do two queries and add the results together, but is there a way, in one query to fetch the non-associated records, plus the associated records that match the condition?

+3  A: 

How about this?

User.all(
  :include => :event, 
  :conditions => ["users.event_id IS NULL OR events.name != ?", "party"])
Sarah Mei
Thanks, Sarah. I had tried the same conditions but with :joins, which didn't work. I feel like an idiot that I didn't think of using :include instead. I live and learn :-).
insane.dreamer