Skip to main content

has_one - find all that have no associated object

·109 words·1 min· ·
General Ruby Rails Has_one Has_many Belongs_to
Ariejan de Vroom
Author
Ariejan de Vroom
Jack of all Trades, Professional Software Craftsman

Let me pose a typical Rails situation:

class Person < ActiveRecord::Base
  has_one :fancy_hat
end

class FancyHat < ActiveRecord::Base
  belongs_to :person
end

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

class Person < ActiveRecord::Base
  has_one :fancy_hat

  named_scope :hatless, :joins => '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 < ActiveRecord::Base
  belongs_to :person

  named_scope :wearerless, :conditions => { :person_id => nil }
end

Related

RSpec'ing with Time.now
·174 words·1 min
General Ruby Rails Rspec Test Time
BaseApp: a quick start for your Rails App
·303 words·2 mins
General Ruby Ruby on Rails Rails BaseApp
ActiveRecord Read Only Model
·209 words·1 min
General Blog Ruby Rails Ror Activerecord