simple exists? question

This has to be simple but I am not able to figure it out.

I only want the :notice data (and <p> tags) to show up in the application layout if there is a notice.

The code below works if there is not a :notice (nothing shows up in code) but gives an error if there is a notice. The error is "undefined method `exists?'".

<% if flash[:notice] :exists? %> <p><%= flash[:notice] %></p> <% end %>

Sunny

I use the following in my ApplicationController for this type of thing:

  def flash_message     if flash[:notice]       %{<div class="notice">#{flash[:notice]}</div>}     elsif flash[:warning]       %{<div class="warning">#{flash[:warning]}</div>}     elsif flash[:note]       %{<div class="note">#{flash[:note]}</div>}     elsif flash[:alert]       %{<div class="alert">#{flash[:alert]}</div>}     elsif flash[:error]       %{<div class="error">#{flash[:error]}</div>}     end   end

then I just call

<%= flash_message %>

from within my view

Adam

There's a syntax problem on the first line. You could do:   <% if flash[:notice].nil? %> or simply: <% if flash[:notice] %>

--Paul

I am puzzled with this if flash[:notice] :exists? construction even it is totally wrong.

You have If condition then .... something or you meant flash[:notice].exists?.

That is also wrong since nil do not respond to exists? Neither does the hash or kernal.

I like Adam's suggestion but had to put the code in the application_helper to get it to work right.

def flash_message    if flash[:notice]      %{<div class="notice">#{flash[:notice]}</div>}    elsif flash[:warning]      %{<div class="warning">#{flash[:warning]}</div>}    elsif flash[:note]      %{<div class="note">#{flash[:note]}</div>}    elsif flash[:alert]      %{<div class="alert">#{flash[:alert]}</div>}    elsif flash[:error]      %{<div class="error">#{flash[:error]}</div>}    end end

then I just call

<%= flash_message %>

from within my view

oops, I meant to say ApplicationHelper and not ApplicationController! Glad you got it figured out.

Adam

Let's DRY this up a bit. How about:

<% [ :message, :notice, :warning, :error ].each do |message| %>     <% if flash[message] %>         <div class="<%= message.to_s %>" id="flash">             <%= flash[message] %>         </div>     <% end %> <% end %>

Hey Sunny, Just to anwser your questions. exists? is not a method, hence your error. What you'll want to do is something like

<%= flash[:notice] if flash[:notice] %>

Which is basically Ruby short hand for <% if flash[:notice] %>   <%= flash[:notice] %> <% end %>

You don't need an exists? method Ruby implies it already, as does javascript for instance. You could also use <%= flash[:notice] unless flash[:notice].blank? %>

As blank? is a method that checks for the presence of nil

Hope this helps, Cam