Uses GET and POST for the new action of a resource

Hi,

I’m trying to make the following routes, but also accept POST for the /quiz/files/new path.

namespace :quiz do
  resources :files
end

#         Prefix Verb   URI Pattern                    Controller#Action
#     quiz_files GET    /quiz/files(.:format)          quiz/files#index
#                POST   /quiz/files(.:format)          quiz/files#create
#  new_quiz_file GET    /quiz/files/new(.:format)      quiz/files#new
# edit_quiz_file GET    /quiz/files/:id/edit(.:format) quiz/files#edit
#      quiz_file GET    /quiz/files/:id(.:format)      quiz/files#show
#                PATCH  /quiz/files/:id(.:format)      quiz/files#update
#                PUT    /quiz/files/:id(.:format)      quiz/files#update
#                DELETE /quiz/files/:id(.:format)      quiz/files#destroy

I was able to make it with the following:

namespace :quiz do
  resources :files, except: :new
end

match "quiz/files/new", via: [:get, :post], as: :new_quiz_file

#         Prefix Verb     URI Pattern                    Controller#Action
#     quiz_files GET      /quiz/files(.:format)          quiz/files#index
#                POST     /quiz/files(.:format)          quiz/files#create
# edit_quiz_file GET      /quiz/files/:id/edit(.:format) quiz/files#edit
#      quiz_file GET      /quiz/files/:id(.:format)      quiz/files#show
#                PATCH    /quiz/files/:id(.:format)      quiz/files#update
#                PUT      /quiz/files/:id(.:format)      quiz/files#update
#                DELETE   /quiz/files/:id(.:format)      quiz/files#destroy
#  new_quiz_file GET|POST /quiz/files/new(.:format)      quiz/files#new

Is there a better way to achieve this?

No there is not, you have to choose if you want resourceful routes or not. Doing a POST to new which just renders a template is against the RESTfull philosophy.

It was what I imagined. I forget to mention why I’m thinking of doing this. My new action is like a wizard, so the user keeps making requests to it with augmented parameters, but one of the steps can submit so much information that extrapolates the length limit for an HTTP GET request.

I want to keep this interaction stateless, so I’m thinking of changing my approach to load the form data through AJAX requests.

If someone has more suggestions about accomplishing this, I’d be glad to hear them.

Best regards!

you interaction can be stateless, but your resource design is not restfull based on your code I would recommend something like a file_wizzard resource that would only do edit, update and on the final update would actualy create the file you do not need to create a model for that, but the controller should handle the file creation process eventually you might find out that having a model for this helps (with a cleanup job to remove unfinished wizzards) and its actually better (addressability)

1 Like