user984621
user984621

Reputation: 48443

Rails 4 ActiveRecord - how to see how is interpreted a database query?

I have these models:

teacher

class Teacher < ActiveRecord::Base
  has_many :days
end

day

class Day < ActiveRecord::Base
  belongs_to :teacher
end

And running these query:

  active_teachers = Teacher.joins(:days).where("teacher.id" => found_teachers.pluck(:teacher_id).uniq, "days.day_name" => selected_day)

What the query (should) does: found_teachers is an array of all teachers with duplications, remove the duplicity and chose only those teachers that have classes on a respective day (selected_day contains a string, Monday for example).

Because the amount of data in the variable active_teachers is so big that I can't manually go record by record (and I am not sure that I built this query properly and it does exactly what I need), I am trying to find out how is this query translated to SQL from ActiveRecord.

Usually I see everything in the terminal where is running server for the Rails app, but as of now, I don't see there this query stated.

So the question is, how can I see how the ActiveRecord query is translated to SQL?

Thank you in advance.

Upvotes: 0

Views: 54

Answers (2)

Kranthi
Kranthi

Reputation: 1417

You can use

ActiveRecord::Base.logger = Logger.new STDOUT

and run your query in rails console. So it prints out the sql queries in the console

Upvotes: 0

apneadiving
apneadiving

Reputation: 115511

To get details from a query you're typing, you can do:

query.to_sql
query.explain

Upvotes: 5

Related Questions