如何在 Ruby on Rails 中查看由给定 ActiveRecord 查询生成的 SQL [英] How can I see the SQL that will be generated by a given ActiveRecord query in Ruby on Rails

查看:22
本文介绍了如何在 Ruby on Rails 中查看由给定 ActiveRecord 查询生成的 SQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想查看给定 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆