如何查看Ruby on Rails中给定ActiveRecord查询将生成的SQL [英] How can I see the SQL that will be generated by a given ActiveRecord query in Ruby on Rails
问题描述
我想查看给定ActiveRecord查询将生成的SQL语句。我知道可以在发出查询后从日志中获取此信息,但是我想知道是否存在可以调用和ActiveRecord查询的方法。
I would like to see the SQL statement that a given ActiveRecord Query will generate. I recognize I can get this information from the log after the query has been issued, but I'm wondering if there is a method that can be called on and ActiveRecord Query.
例如:
SampleModel.find(:all, :select => "DISTINCT(*)", :conditions => ["`date` > #{self.date}"], :limit => 1, :order => '`date`', :group => "`date`")
我想打开irb控制台并在最后添加一个方法,该方法将显示该查询将要显示的SQL
I would like to open the irb console and tack a method on the end that would show the SQL that this query will generate, but not necessarily execute the query.
推荐答案
最后一次尝试执行此操作时,还没有正式的方法。我求助于使用 find
及其朋友用来直接生成其查询的功能。这是私有API,因此Rails 3可能会完全破坏它,但是对于调试来说,这是一个不错的解决方案。
When last I tried to do this there was no official way to do it. I resorted to using the function that find
and its friends use to generate their queries directly. It is private API so there is a huge risk that Rails 3 will totally break it, but for debugging, it is an ok solution.
方法是 construct_finder_sql(options)
( lib / active_record / base.rb:1681
)您将不得不使用 send
,因为它是私有的。
The method is construct_finder_sql(options)
(lib/active_record/base.rb:1681
) you will have to use send
because it is private.
编辑: construct_finder_sql
已从Rails 5.1.0.beta1 中删除。
这篇关于如何查看Ruby on Rails中给定ActiveRecord查询将生成的SQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!