has_one - find all that have no associated object

07 June 2009
Tagged general, ruby, rails, has_one, has_many, belongs_to

Let me pose a typical Rails situation:

class Person 


Now, how can you get all the people that don't have a fancy hat?

class Person  'LEFT JOIN fancy_hats ON fancy_hats.person_id = people.id', :conditions => 'fancy_hats.person_id IS NULL'
end

Now you can find all the hatless people you want.

FYI: Finding fancy hats that have no one to wear them is a lot easier, because the foreign key is stored in the fancy_hats table.

class FancyHat  { :person_id => nil }
end