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?
-
Are you trying to minimize number of actions or something? They're free, you know :) – Sergio Tulentsev Jul 29 '16 at 09:06
2 Answers
is it a bad practice to have a single action for adding new item
Yeah, it kinda is bad practice. For one thing, it goes completely against RESTful principle.
Secondly, it goes against Single Responsibility Principle. If your action handles both things, you'll have to do something along the lines of
def my_custom_action
if request.post?
# create stuff
else
# render form
end
end
This is a trivially avoidable complication of code.
In short, I see no benefits and several disadvantages in doing this.

- 1
- 1

- 226,338
- 43
- 373
- 367
-
how would you name 2 additional actions in a controller then? say, the verb is "call". and you need 2 actions: get and post for "call": show insert and actually insert. – Jul 29 '16 at 09:14
-
What do you mean "verb"? You don't add _verbs_ to collections. You add nouns. – Sergio Tulentsev Jul 29 '16 at 09:16
-
oh my god, is it so difficult to figure out what I mean from the context? you add verbs to controller. verb is action. – Jul 29 '16 at 09:23
-
@Johshi: you are confused. Actions are verbs, yes, but you don't get or create actions. You run them. – Sergio Tulentsev Jul 29 '16 at 09:29
-
@Johshi: "get and post for call: show insert and actually insert" - your words. What does it even _mean_ to "insert a call"? – Sergio Tulentsev Jul 29 '16 at 09:29
-
Must be there's a hidden unnamed noun lurking around here. You have to find and name it. – Sergio Tulentsev Jul 29 '16 at 09:31
-
1@Johshi Did I understand you right, that you don't know how to name the two actions? RESTful would be: `new` action (using GET): render form; `create` action (using POST): create object in db, and usually redirect. – siegy22 Jul 29 '16 at 09:37
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!

- 1,225
- 7
- 16