Rails controller actions ordering convention
Rails scaffold generates the controller actions in this order:
index
show
new
edit
create
update
destroy
GET requests are before the non-GET ones. Not a strict CRUD order but I find it intuitive and easy to follow. (Check the source code.)
Some people (including me) also prefer pairing new
and create
, edit
and update
together as they are more related to each other.
index
show
new
create
edit
update
destroy
I also like to apply either of this order to places where we need to specify some of the actions, such as routes and before_actions.
For example:
# 🙅 Bad
resources :follow, only: %i[destroy create]
namespace :admin do
resources :posts, only: %i[show index update]
end
# 👍 Good
resources :follow, only: %i[create destroy]
namespace :admin do
resources :posts, only: %i[index show update]
end
# 🙅 Bad
before_action :require_login, only: %i[update destroy edit]
# 👍 Good
before_action :require_login, only: %i[edit update destroy]
Is there a Rubocop to ensure the action order?
I've seen many codebases don't have any sort of ordering conventions. Sometimes I encounter a destroy
and then create
. Lacking consistensy makes it hard to navigate the codebase. So I was wondering if there is a Rubocop that checks the controller actions ordering.
Turns out there is a PR https://github.com/rubocop/rubocop-rails/pull/547! 🎉
As of the time of writing (Jan 2022), it's still not merged yet but seems promising. 🙂
Looking at its current implementation, this cop Rubocop::Cop::Rails::ActionOrder
will be disabled by default, understandably. The default order follows Rails scaffold and is also configurable. Nice!
Looking forward to that PR gets merged. 😄
Clap to support the author, help others find it, and make your opinion count.