0

On an unsuccessful save, I would like to redirect to the previous view but with the error message.

redirect_to user_path(@user_id), errors: @user.errors

but in the view, when I check for errors I get an undefined variable errors.

I am not using the same controller new and create, so I can't have @user.errors.any in new.html.erb. I have two different controllers, one in which form is there, and another controller which will take care of create, if the create is not happening I need to redirect to the previous controller.

2
  • You have to set flash[:error] to your expected error message, then you should be able to access it in the views using the same flash[:error]. Commented Sep 18, 2017 at 13:02
  • I don't want to use flash here @Mohanraj Commented Sep 18, 2017 at 13:40

2 Answers 2

1

You may need to use render instead of redirect_to. Something like this:

# controller_1
def step_1
  @user = User.new
  @user.do_something
  ...
end

# controller_2
def step_2
 if @user.save?
   # redirect to another...
 else
   render 'controller_1/step_1`
 end
end

Then on view step_1.html.erb, you can print out errors of @user with @user.errors.

Sign up to request clarification or add additional context in comments.

Comments

0

You have to pass the parameters inside the redirect_to helper like below,

redirect_to user_path(id: @user_id, error: @user.errors.messages)

Please check the rake routes and pass the appropriate key for id, whether it's :id, or :user_id

2 Comments

params[:error] => "#<ActiveModel::Errors:0x007f4ab4014b80>" Okay, Now I am able to get the error in params, but it's coming like this. How do I parse this object?
Yeh I think, i will prefer user.errors.messages .. thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.