Topic: flash notice

Hey all,

Flash notice always appear even before user clicks submit button. Anyone have ideas why?
controller: 
def index
      @contact = Contact.new(params[:contact])
      @contact.save if request.post?
      if @contact.save
      flash[:notice] = 'Contact was successfully created.'
    end
    end
  end

form:
<% form_for :contact, @contact, :url => { :action => 'index' } do |f| %> 
    <%= f.text_field :first_name %> 
    <%= f.text_field :last_name %> 
    <%= f.text_field :organization %> 
    <%= f.text_field :email %> 
    <%= submit_tag "Create" %>
<% end %>

<% if flash[:notice] %>
  <div class="notice"><%= flash[:notice] %></div>
<% end %>

Last edited by johnmerlino (2010-07-26 17:01:29)

Re: flash notice

1. I can't understand why you do save in your 'index' action?
2. Usually and by convention, 'index' is just to show the results (i.e. HTTP GET)
3. By convention it would be better to even separate a 'new' action' (GET) from '''create' action (POST). The below is a classic example:

class UsersController < ApplicationController

def index
        @users = User.find(:all, :order => :name)

        respond_to do |format|
            format.html # index.html.erb
            format.xml  { render :xml => @users }
        end
    end

# GET /users/new GET /users/new.xml
    def new
        @user = User.new

        respond_to do |format|
            format.html # new.html.erb
            format.xml  { render :xml => @user }
        end
    end
# POST /users POST /users.xml
    def create
        @user = User.new(params[:user])

        respond_to do |format|
            if @user.save
                flash[:notice] = "User #{@user.name} was successfully created."
                format.html { redirect_to users_url }
                format.xml  { render :xml => @user, :status => :created, :location => @user }
            else
                format.html { render :action => "new" }
                format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }
            end
        end
    end
end

In your layout file (application.html.erb if you didn't create your own one):

...
<div id="main">
        <% if flash[:notice] -%>
            <div id="notice"><%= flash[:notice] %></div>
        <% end -%>
        <%= yield :layout %>
      </div>