Rails after form submitted redirect to empty form page again

james picture james · Feb 3, 2014 · Viewed 16.4k times · Source

I'm building a page with a simple contact form. After users submit the form, I'd like it to redirect back to that exact same page and then flash a success message. But the reason I'm not using a show is because I want to have a brand new contact form (not what they already submitted), in case they want to submit another request. However, the redirect_to doesn't appear to be working.

Thanks for the help!

My controller (note I've tried render instead of redirect_to as well)

def create
    @contact= Contact.new(secure_params)
    if @contact.save
      flash[:success] = "Thanks! I'll be in touch soon!"
      redirect_to 'new'
    else
      render 'new'
    end
end

My view

<body>
<h1> opening text </h1>

<!--prints success message, making it a hash just in case other messages need to be added in the future -->
<% flash.each do |key, value| %>
    <div class="alert alert-<%= key %>"><%= value %></div>
<% end %>


<%= form_for @contact do |f| %>
<!--form code below -->

Answer

Santhosh picture Santhosh · Feb 3, 2014

Change it to

if @contact.save
  flash[:success] = "Thanks! I'll be in touch soon!"
  redirect_to :action => 'new'
else
  render :action => 'new'
end

redirect_to expects a url/relative path as a string, or a Hash that points to a url

eg:

"/user/10"
"http://localhost:3000/users/new" 
or  {:controller => 'users', :action => 'new'}

But when you give redirect_to 'new', It is looking for '/new'