1

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.

chell
  • 7,646
  • 16
  • 74
  • 140

3 Answers3

1

All you need to do is not use the bang (!) version of update_attributes. Try:

User.transaction do
  if @user.update_attributes(params[:user]) && @board.update_attributes(params[:board])
    ...do stuff...
  else
    render ... (go back to the action the user got here from)
  end
end

Then in your view code put an errors block using a conditional like if @user.errors.any?.

The bang version of update_attribtues and most activerecord methods means it will raise an error if it fails, the regular version just returns false and doesn't save, so you can use that whenever it's ok to fail you just need to take action based on success/failure. Only use the bang version when it's not ok to fail, or when you want to show a 500 screen or something for some reason...

Andrew
  • 42,517
  • 51
  • 181
  • 281
0

I think there is some mistake in the method name @user.update_attributes!(params[:user]) it should be like this @user.update_attributes(params[:user]) or once you need cross check your params values whether it is correct or not else your code looks correct. You can have a help with this update_attributes

Community
  • 1
  • 1
Mukesh Singh Rathaur
  • 12,577
  • 2
  • 23
  • 24
0

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.

Pan Thomakos
  • 34,082
  • 9
  • 88
  • 85