Don’t Create Custom Actions, Create More Resources

Learn why we should not create custom actions in Rails applications.

Example: let’s rate a widget

Suppose we want to allow users to give a widget a rating, say one to five stars. Let’s also suppose we store these ratings aggregated on the widget itself, using the current_rating and num_ratings fields.

This example is contrived to create the problem whose solution we want to discuss, but we’re sure you’ve encountered a similar situation where you have a new action to perform on an existing resource, and it doesn’t quite fit with one of the standard actions.

We know what parameters we need (a widget ID and the user’s rating) but we don’t know what route should receive them because it’s unclear what resource and action are involved

We could use the update action on a widget triggered by a PATCH to the /widgets/1234 route. This would be mostly conventional because a PATCH is a partial modification to a resource. The problem arises if we have lots of different ways to update a widget. Our controller might get complicated because it would need to check what sort of update is actually happening:

Get hands-on with 1200+ tech skills courses.