I want to update multiple record in a database with a single SQL query. There is a method forceUpdate
, which can be used like this:
case class Document(size: Int, var status: String) extends ActiveRecord
object Document extends ActiveRecordCompanion[Document]
Document.forceUpdate(_.size < 100)(_.status := "small")
However, it bypasses the validations and hooks like beforeSave()
. I tried underlying squeryl:
Document.inTransaction {
update(Document.table)(d =>
where(d.size < 100)
set(d.status := "small")
)
}
But it also ignores hooks.
I can't seem to find a method that updates multiple documents at once, while using hooks and validations. Is there at least some workaround?
When you do a partial update, you are updating some unknown number of records that match your criteria without retrieving them. For the hooks to get triggered though, the object getting updated needs to be known (i.e. retrieved). The best alternative I can think of would be to retrieve all of the the objects you are updating and then use a batch update rather than a partial update. This won't be as fast or efficient as the partial update you are doing, but unless you can register your hook in the database I don't know what the alternative would be.