Search code examples
ruby-on-railsupdate-attributes

show error messages from two models when updating Rails


I am updating the attributes of two models from one form.

User.transaction do
          begin
             @user.update_attributes!(params[:user]) 
             @board.update_attributes!(params[:board])
          rescue ActiveRecord::RecordInvalid
        end
      end

When the @user.update_attributes produces an error the transaction is stopped and the error message is shown in the view.

However I want to try to update both @user and @board and get the error messages for both so that the user can correct all their mistakes one time.

How can I do this?

Thank you very much in advance.


Solution

  • You could do the following:

    User.transaction do
      @user.update_attributes(params[:user])
      @board.update_attributes(params[:board])
      raise ActiveRecord::Rollback unless @user.valid? && @board.valid?
    end
    

    This will ensure that both update attribute methods run so that you can get error messages for both objects. If either object is invalid though no changes will be persisted to the database.