2015-02-23 79 views
0

我有一个不使用索引的活动记录查询,导致应用程序超时。手动构建活动记录对象

domain.services.where.not(parent_service_id: nil).group('services.type').select('services.type, count(services.id) as user_count') 

=> [#<ServiceModel id: nil, type: "ServiceModelName">] 

我有强制在parent_service_id

ActiveRecord::Base.connection.execute("SELECT services.type, count(services.id) as user_count FROM services where domain_id = 21227 AND parent_service_id IS NOT NULL GROUP BY services.type") 

=> {"type"=>"ServiceModelName", "user_count"=>"2810"} 

它返回我需要快速的信息索引的使用自定义的SQL命令。但是,它会返回一个散列而不是一个模型。如何构建一个activerecord对象,以便我的方法可以返回类似的结果?

+0

显示从日志的第一条语句生成SQL。 – smathy 2015-02-23 17:05:26

+0

这对我有用[http://m.onkey.org/use-index-with-active-record-finders](http://m.onkey.org/use-index-with-active-record -finders) – 2015-02-23 17:05:58

回答

0

相反的connection.execute,你应该能够做到:

ServiceModel.find_by_sql(sql)