I've setup a flash helper:
def flash_message
flash.each do |key, msg|
content_tag :div, msg, :id => key, :class => 'flash'
end
end
And I've put this in my application.html.erb:
<%= flash_message %>
And it's returning content like this:
{:notice=>"Testing"}
I'm fairly new to rails so this could be an amateur mistake.
You're right, it is an amateur mistake. ;)
Using .each here just iterates over the the messages and creates a div for each one. What you want is to make an array out of the divs and then concatenate them together at the end. Something like this:
def flash_message
flash.map do |key, msg|
content_tag :div, msg, :id => key, :class => 'flash'
end.join
end
You haven't made any mistakes and by creating a helper, you're reducing the amount of code required to do common things which is great for testing and organization.
One suggestion that I have is that you change your setup and make a shared partial to display the code so it's easier to manage. Then have your helper method just proxy the arguments to the partial function call.
First setup your partial (save it as 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>
Then setup your helper methods:
def register_flash_message(key,message)
flash[key]=message
end
def display_flash_messages()
render 'shared/flash_messages', :messages => flash
end
This will make things much easier to maintain and customize. You also won't have to deal with having to build your HTML inside of Ruby since everything's stored inside of a partial.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With