如果 flash name == 'notice' 在 rails 视图中不起作用 [英] if flash name == 'notice' not working in rails view
问题描述
<% 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
.
- When I do
<% if true %>
it works. - When I output the
key
, it saysnotice
.
为什么它不起作用?
推荐答案
对于 Rails 4
及以下,flash key
是一个 Symbol
和对于Rails 4.1
,flash key
是一个String
.我想您正在使用 Rails 4 或以下
并与它们的 String 等效项进行比较,这是您问题的根源.
For Rails 4
and under, flash key
is a Symbol
and for Rails 4.1
, flash key
is a String
. I suppose you are using Rails 4 or under
and comparing against their String equivalents which is root of your problem.
您可以通过两种方式解决:
You can resolve it in two ways:
将密钥从 Symbol 转换为 String,然后将其与 String
notice
或alert
进行比较.这种方式更好,因为稍后当您将 Rails 版本升级到 4.1 时,您将不会再遇到当前的问题.
Convert the key from Symbol to String and then compare it against String
notice
oralert
. This way is better because later when you upgrade the Rails version to 4.1 you won't face the current problem again.
<% if key.to_s == 'notice' %>
<%# .. %>
<% elsif key.to_s == 'alert' %>
<%# ..%>
<% end %>
直接与符号:notice
和:alert
进行比较.这暂时有效,但在升级 Rails 版本时无效.
Directly compare with the symbols :notice
and :alert
. This will work for now but would not work when you upgrade the Rails version.
<% if key == :notice %>
<%# .. %>
<% elsif key == :alert %>
<%# ..%>
<% end %>
这篇关于如果 flash name == 'notice' 在 rails 视图中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!