# Finding all records that don't have child

**URL:** <https://www.ruby-forum.com/t/finding-all-records-that-dont-have-child/184124>\
**Category:** Rails\
**Created:** [February 25, 2010, 2:47pm UTC](https://www.ruby-forum.com/t/finding-all-records-that-dont-have-child/184124 "2010-02-25T14:47:11Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![RailsFun](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/d78d45/32.png) [@RailsFun](https://www.ruby-forum.com/u/RailsFun)\
**Post date:** [February 25, 2010, 2:47pm UTC](https://www.ruby-forum.com/t/finding-all-records-that-dont-have-child/184124/1 "2010-02-25T14:47:11Z")

</div>

I have two classes with a one-to-many relationship, and want to find  
all A records that don’t have any B records. I can’t seem to make a  
B.find(:all, :conditions =\> “blah”) work because the foreign key is in  
A. Any help would be appreciated…

This is essentially what I have:

class A \< ActiveRecord::Base  
has\_many :B  
end

class B \< ActiveRecord::Base  
belongs\_to :A  
end

Am I going to have to do a :join to make this work with one sql  
statement? (Just to move on I wrote the following, but I know it is  
the wrong way to do it, just including so you can see the result I  
want to achieve… )

def self.no\_B  
ret = Array.new

```
self.find(:all, :include => :B ).each do |a|
  ret << a if a.B.empty?
end
ret

```

end

---

<div class="post-metadata">

**Author:** ![RailsFun](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/d78d45/32.png) [@RailsFun](https://www.ruby-forum.com/u/RailsFun)\
**Post date:** [February 25, 2010, 2:52pm UTC](https://www.ruby-forum.com/t/finding-all-records-that-dont-have-child/184124/2 "2010-02-25T14:52:26Z")

</div>

I would use a named\_scope in this instance, assuming the relationship  
fields are completely normal.

So the field that u want to check is the association id is nil.

an example for that would be like this:

named\_scope :unassociated, :conditions =\> “foreignkey\_id IS NULL”

hope that works…
