Johshi Johshi - 4 months ago 7
Ruby Question

One or two actions for adding a new item?

I need a custom action to a controller for adding something. On "get" it shows a form and on post it inserts data and redirects. I wonder, is it a bad practice to have a single action for adding new item? Should I create one for "get" and one for "post" instead?

Answer

It would not be consider as a good practice to use the single method for both displaying form and for submit forms as per the restful routes concept.

But still if you want to do it as per the choice or preference you can do it like below code.

You can create a single method for both get and post method. by using something like this.

match '/customurl' => 'controller#action', via: [:get, :post]

Here you need to write the code accordingly in the method by checking the method is called by get or by post and perform the task accordingly.

Hope this will help!