开发者

ActiveRecord WHERE NOT EXISTS

开发者 https://www.devze.com 2022-12-31 20:33 出处:网络
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.

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
          开发者_JAVA百科          WHERE cities_stores.store_type = stores.store_type)


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消