Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Why does custom url change when `render 'new'` is called?

I have a controller that controls a contact us form on a contact page. Inside the routes.rb file I have a line that says match '/contact', :to => 'feedback#new'. Now when the form is filled out correctly, everything works fine; the url is '/contact'. However, when the form isn't filled out correctly, my controller renders 'new' and the url changes from '/contact' to '/feedback'. Can someone tell me why this happens and how I can fix it so that if the validations are triggered and the page is rendered, the url will be /contact still and not /feedback? Thanks!

My controller code: enter image description here

like image 872
ab217 Avatar asked Feb 08 '11 12:02

ab217


2 Answers

match '/contact', :to => 'feedback#new'

That route will only match /contact to FeedbackController#new.

You will want to add to match the "post" part to FeedbackController#create

match '/contact', :to => 'feedback#create', :via => :post, :as => :post_contact
# change :as => to whatever path for this you'd like to use, ex :as => :create_contact

Your form will now change to

= form_for(@feedback), :url => post_contact_path do |f|

Just using the default form_for will try to create the path from a resources in your routes.rb. And, i'm assuming that route is resources :feedback which will of course create routes that look like /feedback.

like image 144
nowk Avatar answered Sep 18 '22 03:09

nowk


in your routes.rb instead of your /contact matcher use:

resources :contact, :as => :feedback, :controller => :feedback, :only => [:new, :create]

http://guides.rubyonrails.org/routing.html#customizing-resourceful-routes

like image 42
Christopher Manning Avatar answered Sep 21 '22 03:09

Christopher Manning