2

Flash notice is not working. I am using rails 5.1. My code is like this:

def message
  redirect_to users_path, notice: "Message"
end

<% if flash.present? %>
  <% flash.each do |k, v| %>
    <p class="abc" id="a"><%= v %></p>
  <% end %>
<% else %>
  <p class="a" id="b"></p>
<% end %>

Flash Message is coming few times and few times it's not coming, It's going in else block.

So, for this I have fixed by using flash.keep in users index controller. But Now in every page whenever I am redirecting,that flash message is coming.

Imran Ali
  • 2,223
  • 2
  • 28
  • 41
Kumar Nikhil
  • 99
  • 1
  • 11

2 Answers2

0

You can try as:

def message
  flash[:notice] = 'Message'
  redirect_to users_path
end

And in your view:

<% if flash[:notice].present? %>
  <% flash.each do |k, v| %>
    <p class="abc" id="a"><%= v %></p>
  <% end %>
<% else %>
  <p class="a" id="b"></p>
<% end %>

Hope it can solve your problem.

Khanh Pham
  • 2,848
  • 2
  • 28
  • 36
  • It's not working like that. So, I added falsh.keep in users index action. so now every time flash message is coming but when ever I am redirecting to different page, wherever I don't need that flash message there also I am getting that message. – Kumar Nikhil Jan 21 '20 at 07:17
0

I think the flash hash is always present. You can check if it's empty instead https://api.rubyonrails.org/classes/ActionDispatch/Flash/FlashHash.html#method-i-empty-3F

<% if flash.empty? %>
  <p class="a" id="b"></p>
<% else %>
  <% flash.each do |k, v| %>
    <p class="abc" id="a"><%= v %></p>
  <% end %>
<% end %>
arieljuod
  • 15,460
  • 2
  • 25
  • 36