devroom.io/content/posts/2009-06-07-has_one-find-all-that-have-no-associated-object.md
2013-03-24 22:28:43 +01:00

41 lines
1.0 KiB
Markdown

---
title: "has_one - find all that have no associated object"
kind: article
slug: has_one-find-all-that-have-no-associated-object
created_at: 2009-06-07
tags:
- General
- Ruby
- Rails
- has_one
- has_many
- belongs_to
---
Let me pose a typical Rails situation:
<pre lang="ruby">class Person < ActiveRecord::Base
has_one :fancy_hat
end
class FancyHat < ActiveRecord::Base
belongs_to :person
end</pre>
Now, how can you get all the people that don't have a fancy hat?
<pre lang="ruby">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</pre>
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 <code>fancy_hats</code> table.
<pre lang="ruby">class FancyHat < ActiveRecord::Base
belongs_to :person
named_scope :wearerless, :conditions => { :person_id => nil }
end</pre>