views:

42

answers:

1

I have a static_controller that is in charge of all the static pages in the site and works as follows in routes.rb:

map.connect ':id', :controller => 'static', :action => 'show'

I have a static page called about that among other information, has a contact form. I currently have a contacts_controller that is in charge of inserting the contact information to the database. Inside my routes.rb file, I have:

map.resources :contacts

My contact form (simplified) looks like this:

<% form_for @contact do |f| %>
    <p class="errors"><%= f.error_messages %></p>  

    <p>
        <%= f.label :first_name %>
        <%= f.text_field :first_name %>
    </p>


    <p class="buttons"><%= f.submit %></p>
<% end %>

Which in turn submits to the create action of my contacts_controller. My create action looks like this:

def create
    @contact = Contact.new(params[:contact])
    if @contact.save
      flash[:notice] = "Email delivered successfully."
    end
    redirect_to "about"
end

The problem is, is the that when I redirect back to my about page the error_messages for the form get lost (since the error_messages for the form only exist for one request, and that request ends upon redirect). How would I go about preserving the error_messages and still linking the users back to the about static url? Would a session/flash be sufficient (if so, what code would I use to pass error messages) or am I going about this whole thing wrong?

Thanks!

+2  A: 

I think what might be going on is you need to render rather than redirect. Redirect terminates the request, and tells the client to make a new request to a different address. That will lose your errors. If your save attempt fails your want to complete the request by rendering the action again with the errors shown.

def create
@contact = Contact.new(params[:contact])
if @contact.save
  flash[:notice] = "Email delivered successfully."
  redirect_to @contact #make a new request for the address of the new record or some other address if you want
else
  render :action => "new" #complete the request by rendering the new action with the @contact variable that was just created (including the @errors).
end
Mike Williamson
but then i remain on the `/contacts` url instead of `/about` - exactly what i wanted to avoid. This is also not very RESTful. Any suggestions?
yuval
Yes, you will remain on /contacts, which is a POST. This is the standard way to ensure your errors get displayed.
Jonathan Julian
If contact saves you can do "redirect_to :action => 'about'". If the save fails use render. Just remember that @errors won't exist if you ask for a new connection (using redirect).I'm not a REST expert but that code is pretty standard stuff in most Rails apps. My (possibly flawed) understanding is that the important part in REST is that you are acting on the info in the HTTP method not what's in the url. What specifically seems unRESTful?
Mike Williamson