devroom.io/content/posts/2009/2009-06-07-has_one-find-all-that-have-no-associated-object.md

42 lines
1006 B
Markdown
Raw Normal View History

2015-03-26 11:28:08 +00:00
+++
date = "2009-06-07"
title = "has_one - find all that have no associated object"
tags = ["General", "Ruby", "Rails", "has_one", "has_many", "belongs_to"]
slug = "has_one-find-all-that-have-no-associated-object"
+++
Let me pose a typical Rails situation:
2024-01-30 08:26:51 +00:00
```ruby
class Person < ActiveRecord::Base
2015-03-26 11:28:08 +00:00
has_one :fancy_hat
end
class FancyHat < ActiveRecord::Base
belongs_to :person
2024-01-30 08:26:51 +00:00
end
```
2015-03-26 11:28:08 +00:00
Now, how can you get all the people that don't have a fancy hat?
2024-01-30 08:26:51 +00:00
```ruby
class Person < ActiveRecord::Base
2015-03-26 11:28:08 +00:00
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'
2024-01-30 08:26:51 +00:00
end
```
2015-03-26 11:28:08 +00:00
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.
2024-01-30 08:26:51 +00:00
```ruby
class FancyHat < ActiveRecord::Base
2015-03-26 11:28:08 +00:00
belongs_to :person
named_scope :wearerless, :conditions => { :person_id => nil }
2024-01-30 08:26:51 +00:00
end
```
2015-03-26 11:28:08 +00:00