Rails 7.1 Adds --parent Option To The Controller Generator.

Rails provides generators to quickly create files that follow Rails conventions.

The most power-packed one is the scaffold generator which creates a model, controller, views, and tests for a given resource.

Of course, each file can be created individually using the model, controller, and job generators.

Before

The controller generator can be used to create an ApplicationController class, which serves as the base class for all controllers in the application.

Prior to Rails 7.1, It was not possible to directly generate a controller that inherits from a class other than ApplicationController.

We need to manually update the parent class in the controller file after it has been generated.

rails generate controller project/payments

create  app/controllers/project/payments_controller.rb
invoke  erb
create    app/views/project/payments
invoke  test_unit
create    test/controllers/project/payments_controller_test.rb
invoke  helper
create    app/helpers/project/payments_helper.rb
invoke    test_unit
.....

# app/controllers/project/payments_controller.rb
class Project::PaymentsController < ApplicationController
end

# Now we have to manually update the parent controller
class Project::PaymentsController < ProjectController
end

After

Rails 7.1 ships with –parent option for controller generator to specify parent class of controller.

With this we can generate a controller that inherits from the specified parent class.

rails generate controller CONTROLLER_NAME --parent=PARENT_CONTROLLER_NAME
rails generate controller project/payments --parent=project_controller

create  app/controllers/project/payments_controller.rb
invoke  erb
create    app/views/project/payments
invoke  test_unit
create    test/controllers/project/payments_controller_test.rb
invoke  helper
create    app/helpers/project/payments_helper.rb
invoke    test_unit

# app/controllers/project/payments_controller.rb
class Project::PaymentsController < ProjectController
end

Need help on your Ruby on Rails or React project?

Join Our Newsletter