How to See the SQL That Will Be Generated by a Given Activerecord Query in Ruby on Rails

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 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 can I get SQL statement created by ActiveRecord#find without actually executing it?

For Rails 3:

Check out the ActiveRecord::Relation docs at the Rails 3 docs.

# get the relation
rel = User.complex_scope.chained_complex_scope

# get the SQL
# this does not execute the query
sql = rel.to_sql

# find out how many records
# this executes the query behind the scenes
count = rel.size

Ruby on Rails, ActiveRecord query (boss can see the gratitudes that his employees have received.)

Try this, not sure if this will work or not.
I'd suggest changing the following in the gratitudes table.

  • send_to_user_id to receiver_id

  • user_id to sender_id

Assuming that you now have the following association in the Gratitude Model

  • belongs_to :receiver, class_name: 'User', foreign_key: 'receiver_id'

ActiveRecord Query:

Gratitide.joins(:receiver).where(users: { manager: current_user })

Rails: Given an Active_Relation is it possible to determine the query that generated it?

You do have a few public methods for this. I normally inspect using to_sql b/c it tells me what will be executed, which is normally what i'm looking to know.

There is also where_values_hash and joined_includes_values

ActiveRecord: how to query records created on a specific weekday (e.g. on Mondays, Tuesdays, etc)

For postgres you can use date_part where Monday=1, Tuesday=2, etc.

Eg, to find all users created on a Friday you can use:
User.where("DATE_PART('dow', created_at::date)=?",5)



Related Topics



Leave a reply



Submit