简体   繁体   中英

flash[:notice] not showing rails 4

I am trying to show flash message for one of my methods upon submit, it saves and then displays the flash message but it is not doing that.

class PromotionsController < ApplicationController
  def newsletter_signup

    @subscriber = Subscriber.new(params[:subscriber])
    if params[:subscriber][:email].present?
      @subscriber.save
      redirect_to :back
      flash[:notice] = "Thank you. You have subscribed to our newsletter"
    end
  end
end

my view in application.html.erb

<div class="row ">
  <div class="icon-send col-sm-4 col-lg-4 hidden-xs  col-md-4 col-xs-4">
    <span class="text-center subscribeLabel">Subscribe to Our Newletter</span>

 </div>
 <%= form_for(Subscriber.new, url: newsletter_signup_url, :validate => true) do |person_form| %>
     <div class="col-md-6 col-sm-6 col-xs-7">
        <%= person_form.text_field :email, id: "email", class: "SubscibenowText", placeholder: "Enter Your Email Address" %>
     </div>
     <div class="col-md-2 col-sm-2 col-xs-5 SubRelative">
       <button type="submit" class="pull-right btn btn-default subscribebtn">
         GET STARTED
       </button>
     </div>
  <% end %>
</div>

I am not sure what else to do because i have tried different options but all to no avail. I would appreciate any help thanks.

I think it is happening because your page is getting redirected before assigning message into flash[:notice] .

So, In your PromotionsController move your flash[:notice] line before redirect_to .

And I don't see where you are displaying this flash message in your view.

You need to display the flash messages too:

<% unless flash.empty? %>
  <div class="row flash_msg">
    <% flash.each do |name, message| %>
      <div class="text-center alert <%= flash_class(name) %>">
        <button class="close" data-dismiss="alert" type="button">&times;</button>
        <i class="<%= flash_icon(name) %>"></i>
        <%= message %>
      </div>
    <% end %>
  </div>
<% end %>

I did this in application.html.erb to display the flash messages. You can put it inside the application.html.erb file in any div.

And put the flash[:notice] message before redirect_to(:back) in controller method.

Hope this helps!

redirect_to :back uses javascript:history.back() which will not setup the necessary message in your flash to be displayed. Instead try using redirect_to other_page_path . Hope that helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM