Finding all records that don't have child

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

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…

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs