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

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

    I needed to use raw sql because I failed at getting composite_primary_keys to function with activerecord 2.3.8. So in order to access the sqlserver 2000 table with a composite primary key, raw sql was required.

    sql = "update [db].[dbo].[#{Contacts.table_name}] " +
          "set [COLUMN] = 0 " +
          "where [CLIENT_ID] = '#{contact.CLIENT_ID}' and CONTACT_ID = '#{contact.CONTACT_ID}'"
    st = ActiveRecord::Base.connection.raw_connection.prepare(sql)
    st.execute
    

    If a better solution is available, please share.

    0 讨论(0)
  • 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.

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