ActiveRecord不存在

jsp*_*ner 8 activerecord

除了find_by_sql之外,有没有办法在ActiveRecord中使用EXISTS?

我想要一个很好的方法来找到一对多关系中没有关联的所有记录.

SELECT DISTINCT store_type FROM stores
  WHERE NOT EXISTS (SELECT * FROM cities_stores
                    WHERE cities_stores.store_type = stores.store_type)
Run Code Online (Sandbox Code Playgroud)

Fra*_*eil 6

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

ActiveRecord将执行与您在上面输入的查询相同的查询.返回的Store实例将具有单个store_type属性.

  • 如果有一种方法可以使用标准的ActiveRecord方法而不是原始SQL来编写内部查询,那将会很好.那可能吗? (7认同)