Retrieving SQL Queries from Active-Record Queries in Rails 3

Retrieving sql queries from Active-record queries in Rails 3

You can debug ActiveRecord queries from a console.

Hit rails console and enter:

ActiveRecord::Base.logger = Logger.new(STDOUT)

How to show SQL queries run in the Rails console?

Rails 3+

Enter this line in the console:

ActiveRecord::Base.logger = Logger.new(STDOUT)

Rails 2

Enter this line in the console:

ActiveRecord::Base.connection.instance_variable_set :@logger, Logger.new(STDOUT)

How to chain raw SQL queries in Rails OR how to return an ActiveRecord_Relation from a raw SQL query in Rails?

This is a way to get an ActiveRecord_Relation from raw_sql.

It works best if you actually have a model matching the fields you're trying to retrieve, but as you can see with test_attribute, any data will be loaded.

# Just an example query, any query should be ok
query = <<-SQL
SELECT *, TRUE AS test_attribute
FROM users
WHERE sign_in_count < 10
SQL
relation = User.select('*').from("(#{query}) AS users")

relation.class
# User::ActiveRecord_Relation

relation.first.test_attribute
# true

How can I see the SQL that will be generated by a given ActiveRecord query in Ruby on Rails

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.

The method is construct_finder_sql(options) (lib/active_record/base.rb:1681) you will have to use send because it is private.

Edit: construct_finder_sql was removed in Rails 5.1.0.beta1.

How do I get the last SQL query performed by ActiveRecord in Ruby on Rails?

AFAIK, there's no easy way to access the list of queries. Nonetheless you can easily get access to them creating a super simple logger.

If you open the class ActiveRecord::ConnectionAdapters::AbstractAdapter you'll see a method called log. This method is invoked on each query to log the statement. By default, it logs all the statements with the Rails logger.

You can do something like

ActiveRecord::ConnectionAdapters::AbstractAdapter.class_eval do

attr_reader :last_query
alias_method_chain :log, :last_query

def log_with_last_query(sql, name, &block)
@last_query = [sql, name]
log_without_last_query(sql, name, &block)
end

end

Now you can get the query with

ActiveRecord::Base.connection.last_query # => ...

Rails 3: ActiveRecord query with :includes only returns results that have related values in included table?

I thought this would get me what I needed, but it doesn't. Calling feature.assets (with feature as an item returned in my query) does another query to look for all assets related to that feature.

Feature.joins("LEFT OUTER JOIN assets on assets.feature_id = feature.id AND asset.issue_date = #{Date.tomorrow}")

So here's what does work. Seems a little cleaner, too. My Feature model already has a has_many :assets set on it. I've set up another association with has_many :tomorrows_assets that points to Assets, but with a condition on it. Then, when I ask for Feature.all or Feature.name_of_scope, I can specify .includes(:tomorrows_assets). Winner winner, chicken dinner.

has_many :tomorrows_assets,
:class_name => "Asset",
:readonly => true,
:conditions => "issue_date = '#{Date.tomorrow.to_s}'"

I can successfully query Features and get just what I need included with it, only if it matches the specified criteria (and I've set :readonly because I know I'll never want to edit Assets like this). Here's an IRB session that shows the magic.

features = Feature.includes(:tomorrows_assets)
feature1 = features.find_all{ |f| f.name == 'This Feature Has Assets' }.first
feature1.tomorrows_assets
=> [#<Asset id:1>, #<Asset id:2>]

feature2 = features.find_all{ |f| f.name == 'This One Does Not' }.first
feature2.tomorrows_assets
=> []

And all in only two SQL queries.

In Rails, how to get the actual Query when an ActiveRecord query executes

You can see the SQL query that is executed by viewing the development log located in log/development.log. Note that the script/server command tails this log file by default.

  • In Rails 3 you can append a .to_sql method call to the end of the finder to output the SQL.

  • Alternatively, New Relic's free RPM Lite gem lets you see the SQL queries in developer mode as well as lots of other useful performance tuning information.

Rails 3 execute custom sql query without a model

Maybe try this:

ActiveRecord::Base.establish_connection(...)
ActiveRecord::Base.connection.execute(...)


Related Topics



Leave a reply



Submit