ab217
ab217

Reputation: 17160

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

Upvotes: 11

Views: 6019

Answers (2)

Christopher Manning
Christopher Manning

Reputation: 4557

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

Upvotes: 2

nowk
nowk

Reputation: 33171

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.

Upvotes: 10

Related Questions