2010-05-25 73 views
6

除了find_by_sql之外,还有一种方法可以将EXISTS与ActiveRecord一起使用吗?ActiveRecord不存在

我想要一个很好的方式来查找所有没有关联的记录在一对多关系中。

SELECT DISTINCT store_type FROM stores 
    WHERE NOT EXISTS (SELECT * FROM cities_stores 
        WHERE cities_stores.store_type = stores.store_type) 

回答

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

ActiveRecord的将执行相同的查询,你在上面输入的内容。返回的Store实例将具有一个store_type属性。

+7

如果有一种方法使用标准的ActiveRecord方法编写内部查询,而不是原始SQL,那将会很不错。那可能吗? – 2013-07-04 04:28:43

+0

@AndrewCone你尝试使用'join'吗?见官方文件http://guides.rubyonrails.org/active_record_querying.html#using-array-hash-of-named-associations – zhongxiao37 2015-07-08 09:18:31

相关问题