如何访问 update_all 生成的原始 SQL 语句(ActiveRecord 方法)

D1D*_*4D5 4 ruby ruby-on-rails ruby-on-rails-3 rails-activerecord

我只是想知道是否有一种方法可以访问为 update_all ActiveRecord 请求执行的原始 SQL。举个例子,看下面这个简单的例子:

Something.update_all( ["to_update = ?"], ["id = ?" my_id] )
Run Code Online (Sandbox Code Playgroud)

在 Rails 控制台中,我可以看到原始 SQL 语句,所以我猜我可以通过某种方式访问​​它?

PS - 我对 update_all 特别感兴趣,无法将其更改为其他任何内容。

谢谢!

max*_*max 5

如果您查看update_all 实现的方式,您将无法to_sql像调用关系那样调用它,因为它直接执行并返回一个整数(执行的行数)。

除非复制整个方法并更改最后一行,否则无法进入流程或获得所需的结果:

module ActiveRecord
  # = Active Record \Relation
  class Relation
    def update_all_to_sql(updates)
      raise ArgumentError, "Empty list of attributes to change" if updates.blank?

      if eager_loading?
        relation = apply_join_dependency
        return relation.update_all(updates)
      end

      stmt = Arel::UpdateManager.new

      stmt.set Arel.sql(@klass.sanitize_sql_for_assignment(updates))
      stmt.table(table)

      if has_join_values? || offset_value
        @klass.connection.join_to_update(stmt, arel, arel_attribute(primary_key))
      else
        stmt.key = arel_attribute(primary_key)
        stmt.take(arel.limit)
        stmt.order(*arel.orders)
        stmt.wheres = arel.constraints
      end

      #- @klass.connection.update stmt, "#{@klass} Update All"
      stmt.to_sql
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

您看到日志语句的原因是它们是由连接执行语句时记录的。虽然您可以覆盖日志记录,但实际上不可能对单个 AR 方法的调用执行此操作。