Rails 7.1 adds --parent option to the controllers
Rails generators are provided by the framework
and
can be invoked using the rails generate
command
or
its shorthand rails g
.
When using a generator,
you provide some options
and
arguments to specify what you want to generate,
and
Rails will create the necessary files
and
configurations for you.
Rails' common generators are Models, Scaffold, Mailer, Job, Channel, Migration, View, Resource and Controllers. Generators significantly speed up the development process, especially when creating standard components of a Rails application.
The Rails controller generator can be used as below:
rails generate controller ControllerName [action action] [options]
Where ControllerName
is the name of the controller you want to create,
[action action]
represents the optional list of actions you want to
include in the controller.
--skip-routes
,
--no-assets
,
--no-controller-specs
,
and
--template-engine
are a few options that can be passed to the
rails generate controller
command.
Before Rails 7.1
Before Rails 7.1, the controller's generator had no support to specify the parent class. You must manually update the controller file and mention the parent controller.
> rails generate controller admin/users
create app/controllers/admin/users_controller.rb
invoke slim
create app/views/admin/users
invoke rspec
create spec/requests/admin/users_spec.rb
.....
# app/controllers/admin/users_controller.rb
class Admin::UsersController < ApplicationController
end
# if your application has AdminController, you need to edit
# the file and change it to your parent controller. For eg.
class Admin::UsersController < AdminController
end
In Rails 7.1
Rails 7.1 adds the --parent options to controller generator that helps the developer pass the parent controller name.
You must pass --parent=CONTROLLER_NAME
to the rails generate controller
command as below:
> rails generate controller admin/users --parent=admin_controller
create app/controllers/admin/users_controller.rb
invoke slim
create app/views/admin/users
invoke rspec
create spec/requests/admin/users_spec.rb
.....
# app/controllers/admin/users_controller.rb
class Admin::UsersController < AdminController
end
The command generates Admin::UsersController
with the AdminController
as
the parent class.
To know more about this feature,
please refer to this Rails
PR.