I\'m new to rails and am not sure I agree with the way I\'ve things done in some of the tutorials I\'ve gone through. The issue has to do with how to handle invalid form sub
As you've found, by default when you specify resources :things
, the POST path for creating a new thing is at /things
. Here's the output for rake routes
:
things GET /things(.:format) {:action=>"index", :controller=>"things"}
POST /things(.:format) {:action=>"create", :controller=>"things"}
new_thing GET /things/new(.:format) {:action=>"new", :controller=>"things"}
edit_thing GET /things/:id/edit(.:format) {:action=>"edit", :controller=>"things"}
thing GET /things/:id(.:format) {:action=>"show", :controller=>"things"}
PUT /things/:id(.:format) {:action=>"update", :controller=>"things"}
DELETE /things/:id(.:format) {:action=>"destroy", :controller=>"things"}
It sounds like you want something more like this:
create_things POST /things/new(.:format) {:action=>"create", :controller=>"things"}
things GET /things(.:format) {:action=>"index", :controller=>"things"}
new_thing GET /things/new(.:format) {:action=>"new", :controller=>"things"}
edit_thing GET /things/:id/edit(.:format) {:action=>"edit", :controller=>"things"}
thing GET /things/:id(.:format) {:action=>"show", :controller=>"things"}
PUT /things/:id(.:format) {:action=>"update", :controller=>"things"}
DELETE /things/:id(.:format) {:action=>"destroy", :controller=>"things"}
Although not recommended, you can get this result with the following route:
resources :things, :except => [ :create ] do
post "create" => "things#create", :as => :create, :path => 'new', :on => :collection
end
You would also need to modify your forms to make them POST to the correct path.
All that being said, the description of the URLs you have in your question don't sound right. You list the following: After submitting a new thing
(submitting a form at /things/new
),
/things/new
to /things
things#index
This is not the functionality I experience in my own Rails 3 applications. Instead, I find that: After submitting a new thing
(submitting a form at /things/new
),
/things/new
to /things
(this is the same)I know this is an old question, but one approach I've been playing with lately is to submit the form with AJAX, even if it wouldn't otherwise require it. This lets you submit it to the default create/update action as far as the routes go, but the URL in the browser doesn't change. The response can be a simple 200 for success with a link to the /index page or wherever you redirect to on a successful save, or a "400 bad request" with error message(s) if data was invalid.
The biggest downfall is that the display of the error messages and invalid fields is now entirely the responsibility of your client side javascript. This becomes a much smaller problem and can even be a good thing once you're using something like Backbone or KnockoutJS on the client side.