Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails scope to check if association does NOT exist

I am looking toward writing a scope that returns all records that do not have a particular association.

foo.rb

class Foo < ActiveRecord::Base       has_many :bars end 

bar.rb

class Bar < ActiveRecord::Base       belongs_to :foo end 

I want a scope that can find all of the Foo's that dont have any bars. It's easy to find the ones that have an association using joins, but I haven't found a way to do the opposite.

like image 476
Julio G Medina Avatar asked Apr 27 '12 17:04

Julio G Medina


People also ask

What is Arel_table?

The Arel::Table object acts like a hash which contains each column on the table. The columns given by Arel are a type of Node , which means it has several methods available on it to construct queries. You can find a list of most of the methods available on Node s in the file predications.


1 Answers

Rails 4 makes this too easy :)

Foo.where.not(id: Bar.select(:foo_id).uniq) 

this outputs the same query as jdoe's answer

SELECT "foos".*  FROM "foos"  WHERE "foos"."id" NOT IN (   SELECT DISTINCT "bars"."foo_id"   FROM "bars"  ) 

And as a scope:

scope :lonely, -> { where.not(id: Bar.select(:item_id).uniq) } 
like image 63
davegson Avatar answered Oct 08 '22 04:10

davegson