How to display a Rails flash notice upon redirect?

后端 未结 6 1256
天命终不由人
天命终不由人 2021-01-31 01:21

I have the following code in a Rails controller:

flash.now[:notice] = \'Successfully checked in\'
redirect_to check_in_path

Then in the /check_

相关标签:
6条回答
  • 2021-01-31 01:47

    If you are using Bootstrap, this will display a nicely-formatted flash message on the page that's the target of your redirect.

    In your controller:

    if my_success_condition
      flash[:success] = 'It worked!'
    else
      flash[:warning] = 'Something went wrong.'
    end
    redirect_to myroute_path
    

    In your view:

    <% flash.each do |key, value| %>
      <div class="alert alert-<%= key %>"><%= value %></div>
    <% end %>
    

    This will produce HTML like:

    <div class="alert alert-success">It worked!</div>
    

    For available Bootstrap alert styles, see: http://getbootstrap.com/docs/4.0/components/alerts/

    Reference: https://agilewarrior.wordpress.com/2014/04/26/how-to-add-a-flash-message-to-your-rails-page/

    0 讨论(0)
  • 2021-01-31 01:48

    I had the same problem, and your question solved mine, because I had forgotten to include in the /check_in view:

    <p id="notice"><%= notice %></p>
    

    In the controller, just a single line:

    redirect_to check_in_path, :notice => "Successfully checked in"             
    
    0 讨论(0)
  • 2021-01-31 01:58

    Or you can do it in one line.

    redirect_to check_in_path, flash: {notice: "Successfully checked in"}
    
    0 讨论(0)
  • 2021-01-31 02:06

    This will work too

    redirect_to check_in_path, notice: 'Successfully checked in'

    0 讨论(0)
  • 2021-01-31 02:09
    redirect_to new_user_session_path, alert: "Invalid email or password"
    

    in place of :alert you can use :notice

    to display

    0 讨论(0)
  • 2021-01-31 02:10

    Remove the .now. So just write:

    flash[:notice] = 'Successfully checked in'
    redirect_to check_in_path
    

    The .now is specifically supposed to be used when you are just rendering and not redirecting. When redirecting, the .now is not to be used.

    0 讨论(0)
提交回复
热议问题