I am a Rails newbie and have a two-fold question. I recently started
working with authentication. The basic authentication system is
working for me, but I would like to catch errors and exceptions and
display appropriate messages to the user.
The first problem is that when I try to display an error message using
flash[:error]="error message", it doesn't get displayed.
flash[:notice] works all right. Here is the code snippet from the
controller for users where I observe the difference in behaviors.
def create
cookies.delete :auth_token
@user = User.new(params[:user])
@user.save!
self.current_user = @user
redirect_back_or_default('/contigs')
flash[:notice] = "Thanks for signing up!"
rescue Activerecord::RecordInvalid
redirect_back_or_default('/login')
puts invalid.record.errors
flash[:error] = "There was a problem creating your account."
end
The user signup page uses the "create" action of the user controller.
When signup is successful, I get redirected appropriately and the
notice is displayed. However, when signup is unsuccessful, the browser
just displays an error page entitled " NameError in
UsersController#create".
Why does this happen?
Second, on the error page I see the session dump as follows:
:csrf_id: 1023bda9eefd568ab601761908724432
flash: !map:ActionController::Flash::FlashHash
:error: Passwords do not match. Please try again!
:return_to:
So, it seems that the actual error that occurs gets stored in
FlashHash in some way. Can I manually retrieve it and flash it on the
screen?
Are you trying to display flash[:error]? Nothing in the flash is displayed magically. You have to decide to display it yourself (often this happens in the application layout)
I added <%= flash[:error] %> to the layout within an if loop. Now for
the login page, if the authentication fails, it displays an error
message and redirects back to itself.
But for the signup page, I still don't get redirected to '/login' (Now
I have replaced this with '/signup') and I see no flash error message
either. I just see an error page with the following dump.