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

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

    Sometime would be better use name of parent class instead name of table:

    # Refers to the current class
    self.class.unscoped.where(self.class.primary_key => id).update_all(created _at: timestamp)
    

    For example "Person" base class, subclasses (and database tables) "Client" and "Seller" Instead using:

    Client.where(self.class.primary_key => id).update_all(created _at: timestamp)
    Seller.where(self.class.primary_key => id).update_all(created _at: timestamp)
    

    You can use object of base class by this way:

    person.class.unscoped.where(self.class.primary_key => id).update_all(created _at: timestamp)
    

提交回复
热议问题