我已经设置了一个flash助手:
def flash_message
flash.each do |key, msg|
content_tag :div, msg, :id => key, :class => 'flash'
end
end
我已经把它放在我的应用程序中了。html.erb:
<%= flash_message %>
它返回的内容如下:
{:notice=>"Testing"}
我对铁轨还很陌生,所以这可能是一个业余爱好者的错误。
你是对的,这是一个业余错误。;)
在这里使用.each只是对消息进行迭代,并为每个消息创建一个div。您想要的是用div组成一个数组,然后在最后将它们连接在一起。类似这样的东西:
def flash_message
flash.map do |key, msg|
content_tag :div, msg, :id => key, :class => 'flash'
end.join
end
您没有犯任何错误,通过创建一个助手,您减少了做常见事情所需的代码量,这对测试和组织非常有用。
我的一个建议是,你可以更改你的设置,并制作一个共享的部分来显示代码,这样更容易管理。然后让helper方法将参数代理到分部函数调用。
首先设置你的部分(保存为shared/_flash_messages.html.erb):
<div class="flash-messages">
<% if messages && messages.length > 0 %>
<% messages.each do |key, message| %>
<div id="<%= key %>" class="flash"><%= message %></div>
<% end %>
<% else %>
No Messages to display
<% end %>
</div>
然后设置你的助手方法:
def register_flash_message(key,message)
flash[key]=message
end
def display_flash_messages()
render 'shared/flash_messages', :messages => flash
end
这将使事情更容易维护和自定义。您也不必在Ruby中构建HTML,因为所有内容都存储在分部中。
问题是您的助手返回。您必须在变量中返回html代码。
有了这个对我有用的小变化:
def flash_message
html = ""
flash.each do |key, msg|
html << (content_tag :div, msg, :id => key, :class => 'flash')
end
html
end
记住ruby中的最后一行是return。
要在flash消息span上获得关闭按钮,您可以这样做:(可能写得更好):
def flash_helper
content_tag :div, class: "flash-messages" do
flash.map do |key, value|
content_tag :div, class: "alert alert-dismissable alert-#{key}" do
content_tag(:span, '×'.html_safe, class: :close, 'data-dismiss' => 'alert') + value
end
end.join().html_safe
end
end