So I’m updating multiple model objects in one go with something like
this in my controller:
=> Photo.update(params[:photo].keys, params[:photo].values)
When the update fails due to validation errors, how do I detect it?
The Rails API says:
“If the save fails under validations, the unsaved object is still
returned.”
So I can’t simply do this:
=> if Photo.update(params[:photo].keys, params[:photo].values)
“@photo = Photo.find(params[:id])
if @photo.update_attributes(params[:photo])…”
At first glance, that seems great for updating ONE model instance.
But I’m updating multiple objects. Are you suggesting that I should
loop through each of the key-values and check that way, like so:
for params[:photo].each do |id|
@photo= Photo.find(id)
if @photo.update_attributes(params[:photo].values[id])
…
end
end
? (Sorry for the poor code, but you know what I’m getting at, right?)
if @photo.update_attributes(params[:photo].values[id])
...
end
end
? (Sorry for the poor code, but you know what I’m getting at, right?)
Well, I seem to be getting your requirements in pieces, so it’s hard
figuring out how to phrase this
For instance, do you want the whole save operation to stop? If so,
use save! and a transaction I’m not sure how you have your hash
structured, but I’m guessing it’s like:
def foo
Photo.transaction do
params[:photo].each do |id, photo_attributes| @photo = Photo.find(id) @photo.attributes = photo_attributes @photo.save!
end
end
rescue
error handling…
end
When save! fails due to a validation error, it raises an exception and
rolls back the transaction.
Oh, the simple solution is probably to just loop through the photos
after calling Photo.update and checking photos[i].errors.empty?
Sweet, thanks Rick. That certainly answers my question and confirms
that I gotta go about it the ‘hard’ way. Wouldn’t it be nice if
ActiveRecord ‘update’ returned some kind of indication of errors if
any of its attempted ‘saves’ fail? (Nice bit about that
ActiveRecord.errors.empty?, very useful.) Ah well…
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.