How to execute a raw update sql with dynamic binding in rails

后端 未结 8 625
遥遥无期
遥遥无期 2020-11-29 02:03

I want to execute one update raw sql like below:

update table set f1=? where f2=? and f3=?

This SQL will be executed by ActiveRecord:

8条回答
  •  温柔的废话
    2020-11-29 02:49

    ActiveRecord::Base.connection has a quote method that takes a string value (and optionally the column object). So you can say this:

    ActiveRecord::Base.connection.execute(<<-EOQ)
      UPDATE  foo
      SET     bar = #{ActiveRecord::Base.connection.quote(baz)}
    EOQ
    

    Note if you're in a Rails migration or an ActiveRecord object you can shorten that to:

    connection.execute(<<-EOQ)
      UPDATE  foo
      SET     bar = #{connection.quote(baz)}
    EOQ
    

    UPDATE: As @kolen points out, you should use exec_update instead. This will handle the quoting for you and also avoid leaking memory. The signature works a bit differently though:

    connection.exec_update(<<-EOQ, "SQL", [[nil, baz]])
      UPDATE  foo
      SET     bar = $1
    EOQ
    

    Here the last param is a array of tuples representing bind parameters. In each tuple, the first entry is the column type and the second is the value. You can give nil for the column type and Rails will usually do the right thing though.

    There are also exec_query, exec_insert, and exec_delete, depending on what you need.

提交回复
热议问题