In Rails when a resource create action fails and calls render :new, why must the URL change to the resource's index url?

后端 未结 5 1795
死守一世寂寞
死守一世寂寞 2020-12-07 14:40

I have a resource called Books. It\'s listed as a resource properly in my routes file.

I have a new action, which gives the new view the standard:

@         


        
5条回答
  •  半阙折子戏
    2020-12-07 15:22

    It can be fixed by using same url but different methods for new and create action.

    In the routes file following code can be used.

    resources :books do
      get :common_path_string, on: :collection, action: :new
      post :common_path_string, on: :collection, action: :create
    end
    

    Now you new page will render at url

    books/common_path_string

    In case any errors comes after validation, still the url will be same.

    Also in the form instead using

    books_path
    

    use

    url: common_path_string_books_path, method: :post
    

    Choose common_path_string of your liking.

提交回复
热议问题