-1

I'm trying to find out how rails converts a hash such as (This is an example please do not take this literally I threw something together to get the concept by I know this query is the same as User.find(1)):

{
    :select => "users.*",
    :conditions => "users.id = 1",
    :order => "username"
}

Into: SELECT users.* FROM users where users.id = 1 ORDER BY username

The closest thing I can find is ActiveRecord::Base#find_every

 def find_every(options)
   begin
     case from = options[:from]
     when Symbol
       instantiate_collection(get(from, options[:params]))
     when String
       path = "#{from}#{query_string(options[:params])}"
       instantiate_collection(format.decode(connection.get(path, headers).body) || [])
     else
       prefix_options, query_options = split_options(options[:params])
       path = collection_path(prefix_options, query_options)
       instantiate_collection( (format.decode(connection.get(path, headers).body) || []), prefix_options )
     end
   rescue ActiveResource::ResourceNotFound
     # Swallowing ResourceNotFound exceptions and return nil - as per
     # ActiveRecord.
     nil
   end
 end

I'm unsure as to how to modify this to just return what the raw mysql statement would be.

4

1 回答 1

0

因此,经过几个小时的挖掘,我想出了一个答案,虽然它不是很好。

class ActiveRecord::Base
  def self._get_finder_options options
    _get_construct_finder_sql(options)
  end

  private
  def self._get_construct_finder_sql(options)
    return (construct_finder_sql(options).inspect)
  end
end

将此作为扩展添加为您提供了一个可公开访问的方法_get_finder_options,该方法返回原始 sql 语句。

在我的情况下,这是一个复杂的查询被这样包装

SELECT COUNT(*) as count FROM (INSERT_QUERY) as count_table

这样我仍然可以将它与 will_paginate gem 一起使用。这仅在我当前的项目中进行了测试,因此如果您尝试复制,请记住这一点。

于 2013-09-23T20:04:17.623 回答