How to execute arbitrary parameterized SQL in rails

前端 未结 1 1635
长发绾君心
长发绾君心 2021-02-19 15:14

For performance reasons, I need to write a new method in my Rails model that executes some arbitrary SQL:

UPDATE table
   SET col1 = ? AND col2 = ?
   WHERE id =         


        
1条回答
  •  北恋
    北恋 (楼主)
    2021-02-19 15:57

    You could also do this:

    updates = ActiveRecord::Base.send(:sanitize_sql_array, ["name = ? and category = ?", name, category])
    ActiveRecord::Base.connection.execute("update table set #{updates} where id = #{id.to_s.to_i}")
    

    to_s is being called on id before to_i in case it's nil.

    0 讨论(0)
提交回复
热议问题