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

后端 未结 8 623
遥遥无期
遥遥无期 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.

提交回复
热议问题