How can I get SQL statement created by ActiveRecord#find without actually executing it?

前端 未结 5 1668
灰色年华
灰色年华 2020-12-30 21:46

I am using will_paginate with some complicated queries and it is unable to correctly calculate number of total records (in order to display proper number of pag

5条回答
  •  囚心锁ツ
    2020-12-30 22:22

    I know the question asks "without executing it", but the #explain method is super useful and should at least be mentioned here. It is extremely useful for debugging slow queries.

    Note: It does execute the query though.

    http://guides.rubyonrails.org/v3.2.8/active_record_querying.html#running-explain

    $ User.where("users.email LIKE '%longford%'").explain
    
      User Load (0.6ms)  SELECT `users`.* FROM `users` WHERE (users.email LIKE '%longford%')
     => EXPLAIN for: SELECT `users`.* FROM `users` WHERE (users.email LIKE '%gmail%')
    +----+-------------+-------+------+---------------+------+---------+------+------+-------------+
    | id | select_type | table | type | possible_keys | key  | key_len | ref  | rows | Extra       |
    +----+-------------+-------+------+---------------+------+---------+------+------+-------------+
    |  1 | SIMPLE      | users | ALL  | NULL          | NULL | NULL    | NULL |    5 | Using where |
    +----+-------------+-------+------+---------------+------+---------+------+------+-------------+
    1 row in set (0.00 sec)
    

提交回复
热议问题