<% flash.each do |key, msg| %>
<% if key == 'notice' %>
<%= content_tag :div, "<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button> #{key}".html_safe, class: 'alert alert-success alert-dismissable' %>
<% elsif key == 'alert' %>
<%= content_tag :div, "<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button> #{msg}".html_safe, class: 'alert alert-danger alert-dismissable' %>
<% end %>
<% end %>
不适合我。
<% if true %>
时,它有效。key
时,它会显示notice
。为什么不起作用?
答案 0 :(得分:11)
对于Rails 4
及以下,闪存key
为Symbol
,对于Rails 4.1
,闪存key
为String
。我想你正在使用Rails 4 or under
并比较它们的String等价物,这是你问题的根源。
您可以通过两种方式解决此问题:
将密钥从Symbol转换为String,然后将其与String notice
或alert
进行比较。这种方式更好,因为稍后当您将Rails版本升级到4.1时,您将不会再遇到当前问题。
<% if key.to_s == 'notice' %>
<%# .. %>
<% elsif key.to_s == 'alert' %>
<%# ..%>
<% end %>
直接与符号:notice
和:alert
进行比较。这将暂时有效,但在升级Rails版本时无效。
<% if key == :notice %>
<%# .. %>
<% elsif key == :alert %>
<%# ..%>
<% end %>
答案 1 :(得分:0)
Flash提供符号哈希,访问它们的正确方法是:
if key == :notice
elseif key == :alert