Rails 4:如何从控制器中提取select_all查询到模型?

时间:2015-02-12 01:56:20

标签: ruby-on-rails ruby activerecord

我有一个复杂的Class.connection.select_all查询我想从控制器#index中提取到相应模型中的类方法。 (查询很复杂,因为它对子查询数据和其他表有多个LEFT OUTER连接)。

Class.connection.select_all查询在控制器中运行正常,但以下类方法只返回空哈希。

 def self.long_query_name(some_param)
  connection.select_all("Lots of SQL goes here")
end

查询结果(为便于阅读而简化):

ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::OID::Float:0x00000004d3e588,                                                
ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::OID::Date:0x00000004d3dfc0},                                                         
 @columns=                                                                                                                                                         
  ["expected/correct column headers"],                                                                                                                                             
 @hash_rows=nil,                                                                                                                                                   
 @rows=[]> 

为什么这不起作用的任何想法?

1 个答案:

答案 0 :(得分:2)

一个简单的find_by_sql应该是这个工作:

def self.long_query_name(some_param)
  find_by_sql("Lots of SQL goes here")
end