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

后端 未结 8 645
遥遥无期
遥遥无期 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:42

    You should just use something like:

    YourModel.update_all(
      ActiveRecord::Base.send(:sanitize_sql_for_assignment, {:value => "'wow'"})
    )
    

    That would do the trick. Using the ActiveRecord::Base#send method to invoke the sanitize_sql_for_assignment makes the Ruby (at least the 1.8.7 version) skip the fact that the sanitize_sql_for_assignment is actually a protected method.

提交回复
热议问题