I want to be able to pass multiple messages to the flash hash, inside of my controller, and have them display nicely together, e.g., in a 开发者_运维知识库bulleted list. The way I've devised to do this is to create a helper function in my Application Controller, which formats an array into a bulleted list, which I then pass to, in my case, flash[:success]. This is clearly not the Rails Way because, i.a., my bulleted list gets encoded. That is, instead of getting:
- Message 1
- Message 2
I get:
<ul><li>Message 1</li><li>Message 2</li></ul>
I'm sure I could figure out a way to raw() the output, but isn't there a simple way to get something like this working? Perhaps there's an option to pass to flash[]? Something else?
I used render_to_string
and a partial instead of a helper to achieve something similar.
# app/controller/dogs_controller.rb
def create
@dog = Dog.new(params[:dog])
@messages=[]
if @dog.save
@messages << "one"
@messages << "two"
flash[:notice] = render_to_string( :partial => "bulleted_flash")
redirect_to(dogs_path)
else
render :action => 'new
end
end
Then I format the array of flash messages in an HTML list
# app/views/dogs/_bulleted_flash.html.erb
<ol>
<% @messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ol>
Which produces the following HTML
# http://0.0.0.0:3000/dogs
<body>
<div id="flash_notice">
<ul>
<li>one</li>
<li>two</li>
</ul>
</div>
...
</body>
If you need to continue using a helper then I think you need to append the html_safe
method to your string to prevent it from being encoded (which rails 3 does by default). Here is a question showing how to use html_safe
in a similar fashion
If you are using Rails3, try the raw method.
raw(my_html_string)
And it won't escape the html. Oh, sorry, I just read your last sentence. Check out this information, "Rails 3 flash message problems", it looks like it may be what you are looking for:
http://www.ruby-forum.com/topic/215108
Usually I would ask for more information about your views and layouts in this situation, because scaffolding doesn't display flash[:success]
by default.
The way I solve this is to totally redo my flash messages usually, by making the flash[:whatever]
an array every time, and in my layout handling that array instead of just the notice. Remember that flash is just a Hash, you're just setting values.
However if you just want to do this with the setup you have now (helper putting the HTML inside the flash[:success]
), you can change the way that the flash messages are displayed in your layout file. By default they are just use <%= flash[:success] %>
, which automatically escapes HTML. To make it not do that for the flash messages, change it to <%=raw flash[:success] %>
精彩评论