What are controllers in Rails and what is their role?

Controllers are a fundamental component of the Ruby on Rails MVC (Model-View-Controller) architecture, acting as intermediaries between models and views. They handle incoming HTTP requests, process data, and determine appropriate responses. For more on MVC architecture, check out our guide on convention over configuration in Rails.

Understanding Controllers in Rails

Controllers in Rails inherit from ApplicationController and contain actions (methods) that handle specific requests. Each action typically corresponds to a particular route and view. For more on routing, see our guide on understanding config/routes.rb file in Rails.

Basic Controller Structure

ruby
1class ArticlesController < ApplicationController
2 def index
3 @articles = Article.all
4 end
5
6 def show
7 @article = Article.find(params[:id])
8 end
9end
10

For more on handling parameters, check out our guide on controller params hash purpose.

Controller Actions and Their Responsibilities

Controllers typically handle seven RESTful actions:

  1. index: Lists all resources
  2. show: Displays a specific resource
  3. new: Shows form for creating a new resource
  4. create: Creates a new resource
  5. edit: Shows form for editing an existing resource
  6. update: Updates an existing resource
  7. destroy: Deletes a resource

For more on RESTful actions, see our guide on RESTful routing in Rails.

Example of a Full RESTful Controller

ruby
1class ProductsController < ApplicationController
2 before_action :set_product, only: [:show, :edit, :update, :destroy]
3
4 def index
5 @products = Product.all
6 end
7
8 def show
9 end
10
11 def new
12 @product = Product.new
13 end
14
15 def create
16 @product = Product.new(product_params)
17 if @product.save
18 redirect_to @product, notice: 'Product was successfully created.'
19 else
20 render :new
21 end
22 end
23
24 def edit
25 end
26
27 def update
28 if @product.update(product_params)
29 redirect_to @product, notice: 'Product was successfully updated.'
30 else
31 render :edit
32 end
33 end
34
35 def destroy
36 @product.destroy
37 redirect_to products_url, notice: 'Product was successfully deleted.'
38 end
39
40 private
41
42 def set_product
43 @product = Product.find(params[:id])
44 end
45
46 def product_params
47 params.require(:product).permit(:name, :description, :price)
48 end
49end
50

For more on parameter handling, see our guide on handle parameters in Rails controllers.

Controller Filters

Filters are methods that run before, after, or around controller actions. They help keep code DRY and handle common tasks like authentication. For more on filters, check out our guide on types of filters in Rails controllers.

ruby
1class ApplicationController < ActionController::Base
2 before_action :authenticate_user!
3 after_action :log_action
4 around_action :wrap_in_transaction
5
6 private
7
8 def authenticate_user!
9 # Authentication logic
10 end
11
12 def log_action
13 # Logging logic
14 end
15
16 def wrap_in_transaction
17 ActiveRecord::Base.transaction do
18 yield
19 end
20 end
21end
22

Strong Parameters

Controllers use strong parameters to whitelist which parameters are allowed, preventing mass assignment vulnerabilities. For more on strong parameters, see our guide on understanding strong parameters in Ruby on Rails.

ruby
1def article_params
2 params.require(:article).permit(:title, :body, :published)
3end
4

Routing and Controllers

Routing in Rails is accomplished through a dedicated configuration file, routes.rb. The routes file defines the mappings of HTTP requests to controller actions. For example, when a user navigates to /users, the request is routed to the index action of the UsersController. For more on routing, check out our guide on Rails routing from the outside in.

ruby
1Rails.application.routes.draw do
2 resources :users
3end
4

This single route declaration creates routes for all the standard RESTful actions (index, show, new, create, edit, update, destroy) for the users resource.

Performance Optimization and Best Practices

Working efficiently with controllers involves following best practices such as keeping controllers thin and models fat. This means that controllers should focus primarily on orchestrating actions and leave business logic computations to models. For more on performance, see our guide on best practices for high-performing APIs in Rails.

Consider implementing utility services or helper modules if a controller starts handling too much logic, ensuring a clear separation of concerns within your application.

Related Resources

Controllers and Routing

Parameter Handling

Architecture and Best Practices

Conclusion

Controllers are a vital part of the Rails MVC architecture, handling user requests and managing application flow. By understanding their role and following best practices, you can build maintainable and efficient Rails applications. Remember to keep controllers focused on their primary responsibility of coordinating between models and views while delegating complex business logic to appropriate models or service objects.

Suggested Articles