Reputation: 516
In my rails 3 project, I'm trying to create a consistent error/success message display dialog to go in the header of my page. I have it displaying flash messages when they are set from controllers, like this:
<% if flash.length > 0 %>
<% flash.each do |key, value| %>
<% if key == "error" %>
<div class="notice error"><%= value %></div>
<% elsif key == "success" %>
<div class="notice success"><%= value %></div>
<% else %>
<div class="notice regular"><%= value %></div>
<% end %>
<% end %>
<% end %>
But, I want to also be able to send custom messages to my dialog that come from link_to tags, for example:
<% if [certain variable is set] %>
<% message = Hash.new %>
<% message[type] = "specific message to be sent with this link" %>
<%= link_to [Link option one] %>
<% else %>
<%= link_to [Link option two] %>
<% end %>
where "type" is either "error", "success", or something else.
when I try to accomplish this by manually putting the message in the flash hash like this:
<% flash[:error] = "specific message to be sent with this link" %>
<%= link to [Link option one] %>
...the message shows up when the user clicks the link, but isn't removed after the user clicks other links. The message remains in the flash hash despite my attempts to remove it manually. The message shows up in the header no matter what page the user goes to, even if the flash hash doesn't have anything new added to it.
When I try the code with the "message" hash above, by testing for "message" in my header and sending it from wherever I want, the hash called "message" isn't set on all pages (only the page I send it to). This understandably results in the error of
undefined local variable or method 'message'
whenever 'message' is not specifically set in the page. I've tried things like
<% if message %>
<%# show error message %>
<% end %>
and
<% if !message.nil? %>
etc
but I still get the undefined error.
Is there a way I can either
a) manually clear a specific hash value after sending it manually,
b) stop the "undefined variable" error from occurring when 'message' is undefined,
or
c) solve this problem in another way?
Thanks so much!
Upvotes: 0
Views: 1436
Reputation: 14222
The message is always showing up because you are always setting the flash[:error]
when "certain variable is set." The flash in this case has no relationship with the link_to
whatsoever. You should be setting flash[:error]
in your controller for whatever action that link_to
is pointing to.
An abundance of logic in your view (as seen above) is a code smell. You should avoid this whenever possible (in this case by putting the flash logic in your controller).
Upvotes: 1
Reputation: 34350
Here are some things you can do:
Upvotes: 0