Catch validation errors from Model.update(params[:object].keys, params[:object].values)

Hi there

I'm trying to update three records at a time with params coming back from an HTML form. The form is set up fine and the params hash is coming back in a form ready to use:

Model.update(params[:object].keys, params[:object].values)

However, I can't catch the validation errors if the objects aren't updated.

In my controller I have this:

if Discount.update(params[:discounts].keys, params [:discounts].values)   flash[:notice_good] = "Discounts have been updated"   redirect_to :action => 'index' else   flash[:notice_bad] = "Couldn't update discounts"   redirect_to :action => 'index' and return false end

I have <%= error_messages_for :discount %> in my view but can't seem to display any validation errors.

Furthermore, it seems that my condtional "if Discount.update [...] etc" fails if there are any errors in saving the updated data to the database.

Any clues on how to properly use Model.update with a params hash would be appreciated.

Richard

I don't see why this should be working at all. If you take a look at the documentation for ActiveRecord::Base.update (http:// api.rubyonrails.org/classes/ActiveRecord/Base.html#M002215) it takes two arguments. id and attributes, so you should really be calling the method like this:

if Discount.update(params[:id], params[:discounts])   flash[:notice_good] = "Discounts have been updated"   redirect_to :action => 'index' else   flash[:notice_bad] = "Couldn't update discounts"   redirect_to :action => 'index' and return false end

Furthermore, you need to save the model in an instance variable in order to display any error messages, *and* error messages will not be saved from request to request, so you need to do a render instead of a redirect:

@discount = Discount.find(params[:id]) if @discount.update(params[:discount])   flash[:notice] = "Discounts have been updated"   redirect_to :action => "index" else   render :action => "new" end

Put <%= error_messages_for :discount %> in new.html.erb.

I can recommend the book "Agile Web Development with Rails" from Pragmatic Programmers to get started with Rails and get the hang of all the concepts of the framework.

Read the docs again. It can update multiple objects and there;s even an example in the docs. update will return an array of the activerecord objects that it tried to update, you can iterate over those and display errors for them, eg

error_message_for 'discount', :object => some_array_of_active_recored_objects

You don't want to redirect though.

Fred