Chowlett
Chowlett

Reputation: 46667

Validate a batch of updates

In a Rails app, is it possible to make a batch of changes all at once, validating only the end result of the changes rather than each individual step?

That was a slightly nebulous question, so let's make it concrete. Suppose I have a grocer's store app:

class Store < ActiveRecord::Base
  has_many :fruits
end

class Fruit < ActiveRecord::Base
  belongs_to :store
  attr_accessible :kind, :number, :price
  validates_uniqueness_of :kind, :scope => :store_id
end

I've seeded the database with the following data:

fruits:
 store_id |    kind    | number | price
----------------------------------------
        1 | apple      |     10 | 0.15
        1 | banana     |     80 | 0.02
        1 | cherry     |     25 | 0.50

But I realise I've messed up, and swapped the number and price of bananas and cherries. I can't do this:

store = Store.find(1)
old_bananas = store.fruits.where("kind = banana").first
old_cherries = store.fruits.where("kind = cherry").first
old_bananas.kind = "cherry"
old_cherries.kind = "banana"
old_bananas.save! # => Validation Error
old_cherries.save!

because the uniqueness constraint is violated when saving the first row, even though it'd be fine after saving the second. Is it possible to batch both saves together, and have the validation see only the result of making all the changes at once?

(I can think of workarounds - for instance, if I made the validation :allow_nil, then nil off each row before changing any of them - but I'd like to know if a "proper" solution exists)

Upvotes: 4

Views: 1106

Answers (1)

Thilo
Thilo

Reputation: 17735

If your constraint is only the validation, but you have no unique index enforcing that in the database, use the update_attribute method - it skips validations.

store.fruits.where("kind = banana").first.update_attribute(:kind, "cherry")
store.fruits.where("kind = cherry").first.update_attribute(:kind, "banana")

Or simply use save(validate: false) instead of save!.

EDIT: Since you have a unique index, the dead simple solution is to use a temporary value:

store.fruits.where("kind = banana").first.update_attribute(:kind, "foo")
store.fruits.where("kind = cherry").first.update_attribute(:kind, "banana")
store.fruits.where("kind = foo"   ).first.update_attribute(:kind, "cherry")

I'm not aware of a way to swap values between rows in-place in SQL, which is really the problem here as the model-level validations can easily be bypassed.

Upvotes: 1

Related Questions