Last updated

has_one - find all that have no associated object

Let me pose a typical Rails situation:

1class Person < ActiveRecord::Base
2  has_one :fancy_hat
3end
4
5class FancyHat < ActiveRecord::Base
6  belongs_to :person
7end

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

1class Person < ActiveRecord::Base
2  has_one :fancy_hat
3
4  named_scope :hatless, :joins => 'LEFT JOIN fancy_hats ON fancy_hats.person_id = people.id', :conditions => 'fancy_hats.person_id IS NULL'
5end

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.

1class FancyHat < ActiveRecord::Base
2  belongs_to :person
3
4  named_scope :wearerless, :conditions => { :person_id => nil }
5end