The correct way to handle invalid form submissions in Rails

前端 未结 2 1044
借酒劲吻你
借酒劲吻你 2021-01-12 02:20

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

2条回答
  •  盖世英雄少女心
    2021-01-12 03:04

    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),

    1. The URL changes from /things/new to /things
    2. Clicking back prompts to resubmit the form
    3. Refreshing shows 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),

    1. The URL changes from /things/new to /things (this is the same)
    2. Clicking back takes the user back to the non-submitted form (no request for a re-post)
    3. Refreshing prompts to resubmit the form (as expected in my opinion)

提交回复
热议问题