Reputation: 14833
I have a redirect in an ApplicationController
-method and want to send a notice through:
class ApplicationController < ActionController::Base
def redirect_if_no_user
if current_user.nil?
redirect_to root_path, notice: t('errors.session_expired')
end
end
end
I'm calling redirect_if_no_user
in some other controller actions.
Unfortunately I cannot see a notice until I do another reload on the homepage manually (After I already got redirected to it via the method). Is this behaviour intended? Anyone got an idea?
Upvotes: 2
Views: 1392
Reputation: 36880
I've had this problem before...
The flash notice you're seeing (eventually) is likely NOT the one you think it is. You have
redirect_to root_path
But I would wager that your root_path has it's own redirect, and that redirect means you've lost the flash notice. When you then submit on root_path you're doing another call on redirect_if_no_user and this time you see the flash message.
You can usually work around this (a redirect following a redirect losing flash message)
with the flash.keep
method.
def my_root_path_action
flash.keep
...
end
... or it might be needed in one of your before_action
or before_filter
methods if they're redirecting before your action is called.
Upvotes: 1
Reputation: 3165
From rails documentation, ( http://guides.rubyonrails.org/action_controller_overview.html#the-flash )
By default, adding values to the flash will make them available to the next request, but sometimes you may want to access those values in the same request. For example, if the create action fails to save a resource and you render the new template directly, that's not going to result in a new request, but you may still want to display a message using the flash. To do this, you can use flash.now in the same way you use the normal flash:
flash.now[:notice] = t('errors.session_expired')
redirect_to root_path
Upvotes: 2
Reputation: 76784
It looks like you might benefit from flash.now
.
I've had issues like that which you mentioned (no flash on redirect), and I haven't solved it entirely yet. One thing I did find was using flash.now
to help someone else solve their issue:
#app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
def redirect_if_no_user
if !user_signed_in? #-> assuming you're using devise
flash.now[:notice] = t('errors.session_expired')
redirect_to root_path
end
end
end
This may not work. If it doesn't, I'll delete.
Upvotes: 1
Reputation: 232
flash[:notice] = t('errors.session_expired')
redirect_to root_path
Try that.
Upvotes: 0