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

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

    Here's a trick I recently worked out for executing raw sql with binds:

    binds = SomeRecord.bind(a_string_field: value1, a_date_field: value2) +
            SomeOtherRecord.bind(a_numeric_field: value3)
    SomeRecord.connection.exec_query <<~SQL, nil, binds
      SELECT *
      FROM some_records
      JOIN some_other_records ON some_other_records.record_id = some_records.id
      WHERE some_records.a_string_field = $1
        AND some_records.a_date_field < $2
        AND some_other_records.a_numeric_field > $3
    SQL
    

    where ApplicationRecord defines this:

    # Convenient way of building custom sql binds
    def self.bind(column_values)
      column_values.map do |column_name, value|
        [column_for_attribute(column_name), value]
      end
    end
    

    and that is similar to how AR binds its own queries.

提交回复
热议问题