Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord WHERE NOT EXISTS

Tags:

activerecord

Is there a way to use EXISTS with ActiveRecord besides find_by_sql?

I'd like a nice way to find all records without an association in a One-to-Many relationship.

SELECT DISTINCT store_type FROM stores
  WHERE NOT EXISTS (SELECT * FROM cities_stores
                    WHERE cities_stores.store_type = stores.store_type)
like image 411
jspooner Avatar asked May 25 '10 22:05

jspooner


1 Answers

Store.all(:select => "DISTINCT store_type",
          :conditions => "NOT EXISTS (SELECT * FROM cities_stores WHERE cities_stores.store_type = stores.store_type)")

ActiveRecord will execute the same query as what you entered above. The returned Store instances will have a single store_type attribute.

like image 133
François Beausoleil Avatar answered Nov 13 '22 22:11

François Beausoleil