How do you detect if ActiveRecord 'update' fails?


#1

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)

Any suggestions?


#2

On 12/27/05, Justin R. removed_email_address@domain.invalid wrote:

Any suggestions?
@photo = Photo.find(params[:id])
if @photo.update_attributes(params[:photo])…


rick
http://techno-weenie.net


#3

@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?)


#4

On 12/27/05, Justin R. removed_email_address@domain.invalid wrote:

    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 :slight_smile:

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:

params[:photo] = {
1 => { photo_params },
2 => { photo_params }…
}

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?


rick
http://techno-weenie.net


#5

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…