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

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

    Why use raw SQL for this?

    If you have a model for it use where:

    f1 = 'foo'
    f2 = 'bar'
    f3 = 'buzz'
    YourModel.where('f1 = ? and f2 = ?', f1, f2).each do |ym|
      # or where(f1: f1, f2: f2).each do (...)
      ym.update(f3: f3) 
    end
    
    

    If you don't have a model for it (just the table), you can create a file and model that will inherit from ActiveRecord::Base

    class YourTable < ActiveRecord::Base
      self.table_name = 'your_table' # specify explicitly if needed
    end
    

    and again use where the same as above:

提交回复
热议问题