| name | rails-action-controller-patterns |
| user-invocable | false |
| description | Use when action Controller patterns including routing, filters, strong parameters, and REST conventions. |
| allowed-tools | ["Read","Write","Edit","Grep","Glob","Bash"] |
Rails Action Controller Patterns
Master Action Controller patterns for building robust Rails controllers with
proper routing, filters, parameter handling, and RESTful design.
Overview
Action Controller is the component that handles web requests in Rails. It
processes incoming requests, interacts with models, and renders responses.
Controllers follow the MVC pattern and implement REST conventions by default.
Installation and Setup
Generating Controllers
rails generate controller Posts index show new create edit update destroy
rails generate controller Admin::Posts index show
rails generate controller Api::V1::Posts --no-helper --no-assets
Routing Configuration
Rails.application.routes.draw do
resources :posts
resources :posts do
resources :comments
end
namespace :admin do
resources :posts
end
get 'about', to: 'pages#about'
root 'posts#index'
end
Core Patterns
1. Basic Controller Structure
class PostsController < ApplicationController
before_action :authenticate_user!, except: [:index, :show]
before_action :set_post, only: [:show, :edit, :update, :destroy]
before_action :authorize_post, only: [:edit, :update, :destroy]
def index
@posts = Post.includes(:user)
.order(created_at: :desc)
.page(params[:page])
end
def show
@comments = @post.comments.includes(:user)
end
def new
@post = Post.new
end
def create
@post = current_user.posts.build(post_params)
if @post.save
redirect_to @post, notice:
render ,
.update(post_params)
redirect_to ,
render ,
.destroy
redirect_to posts_url,
= .find(params[])
.user == current_user
redirect_to posts_path,
params.().permit(, , , [])
2. Strong Parameters
class UsersController < ApplicationController
def user_params
params.require(:user).permit(:name, :email, :password)
end
def user_params_with_profile
params.require(:user).permit(
:name, :email,
profile_attributes: [:bio, :avatar, :website]
)
end
def post_params
params.require(:post).permit(
:title, :body,
tag_ids: [],
images: []
)
end
def user_params
permitted = [:name, :email]
permitted << :admin if current_user.admin?
params.require(:user).permit(*permitted)
end
def organization_params
params.require().permit(
,
[
, , ,
[, , , ]
]
)
params.().permit(
[, , ],
{}
)
3. Filters and Callbacks
class ApplicationController < ActionController::Base
before_action :authenticate_user!
before_action :configure_permitted_parameters, if: :devise_controller?
before_action :set_time_zone, if: :user_signed_in?
after_action :log_activity
after_action :set_cache_headers
around_action :measure_action_time
private
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:name])
end
def set_time_zone
Time.zone = current_user.time_zone
end
def log_activity
ActivityLogger.log(controller_name, action_name, current_user)
end
def set_cache_headers
response.headers['Cache-Control'] = 'no-cache, no-store'
end
def measure_action_time
start = Time.current
yield
duration = Time.current - start
Rails.logger.info "Action took #{duration}s"
<
skip_before_action , [, ]
before_action , [, , ]
before_action , [, ]
prepend_before_action
append_before_action , []
redirect_to root_path .user == current_user
= .all
.increment!()
4. RESTful Conventions
Rails.application.routes.draw do
resources :posts do
collection do
get :drafts
get :search
end
member do
post :publish
patch :archive
end
resources :comments, only: [:create, :destroy]
end
resources :authors do
resources :books, shallow: true
end
resources :users, only: [:index, :show]
resources :sessions, except: [:edit, :update]
resources :posts, path: 'articles'
end
class PostsController < ApplicationController
def drafts
@posts = current_user.posts.draft
render
= .search(params[])
render
= .find(params[])
.publish!
redirect_to ,
redirect_to ,
5. Rendering Responses
class PostsController < ApplicationController
def show
@post = Post.find(params[:id])
respond_to do |format|
format.html
format.json { render json: @post }
format.xml { render xml: @post }
format.pdf { render pdf: @post }
end
end
def create
@post = Post.new(post_params)
if @post.save
redirect_to @post, notice: 'Created'
redirect_back fallback_location: root_path, notice: 'Created'
else
render :new, status: :unprocessable_entity
end
end
def export
render plain: 'Export complete'
render json: { },
head
send_file ,
,
,
send_data generate_csv, ,
,
render , { }
render ,
render ,
render
6. Error Handling
class ApplicationController < ActionController::Base
rescue_from ActiveRecord::RecordNotFound, with: :not_found
rescue_from ActiveRecord::RecordInvalid, with: :unprocessable_entity
rescue_from ActionController::ParameterMissing, with: :bad_request
rescue_from Pundit::NotAuthorizedError, with: :forbidden
private
def not_found(exception)
respond_to do |format|
format.html { render 'errors/404', status: :not_found }
format.json { render json: { error: exception.message },
status: :not_found }
end
end
def unprocessable_entity(exception)
render json: { errors: exception.record.errors },
status: :unprocessable_entity
end
def bad_request(exception)
render { exception.message },
respond_to ||
format.html { render , }
format.json { render { },
}
7. Session and Cookie Management
class SessionsController < ApplicationController
def create
user = User.find_by(email: params[:email])
if user&.authenticate(params[:password])
session[:user_id] = user.id
cookies.signed[:user_id] = user.id
cookies.encrypted[:user_token] = user.token
cookies.permanent[:remember_token] = user.remember_token
cookies[:preference] = {
value: 'dark_mode',
expires: 1.year.from_now,
domain: '.example.com',
secure: Rails.env.production?,
httponly: true
}
redirect_to root_path
else
flash.now[:alert] = 'Invalid credentials'
render :new
end
end
def destroy
session.delete(:user_id)
reset_session
cookies.delete(:user_id)
cookies.delete(:remember_token)
redirect_to login_path
<
||= .find_by( session[])
current_user.present?
helper_method ,
8. Flash Messages
class PostsController < ApplicationController
def create
@post = Post.new(post_params)
if @post.save
flash[:notice] = 'Post created'
redirect_to @post
redirect_to @post, notice: 'Post created'
flash[:success] = 'Operation succeeded'
flash[:error] = 'Something went wrong'
flash[:warning] = 'Be careful'
flash[:info] = 'FYI'
flash.now[:alert] = 'Validation failed'
render :new
end
end
def update
if @post.update(post_params)
flash[:custom_message] = 'Custom notification'
redirect_to @post
else
flash.keep
redirect_to edit_post_path(@post)
end
end
end
<%
<% flash.each || %>
<div =>
<%= message %>
<
9. API Controllers
module Api
module V1
class BaseController < ActionController::API
include ActionController::HttpAuthentication::Token::ControllerMethods
before_action :authenticate
rescue_from ActiveRecord::RecordNotFound do |e|
render json: { error: e.message }, status: :not_found
end
private
def authenticate
authenticate_or_request_with_http_token do |token, options|
@current_user = User.find_by(api_token: token)
end
end
def current_user
@current_user
end
end
end
end
module Api
module V1
class PostsController < BaseController
def index
@posts = .page(params[]).per()
render ,
pagination_meta(),
= .find(params[])
render ,
= current_user.posts.build(post_params)
.save
render , , api_v1_post_url()
render { .errors },
= current_user.posts.find(params[])
.update(post_params)
render ,
render { .errors },
= current_user.posts.find(params[])
.destroy
head
params.().permit(, , )
()
{
collection.current_page,
collection.total_pages,
collection.total_count
}
10. Streaming Responses
class ReportsController < ApplicationController
include ActionController::Live
def export
response.headers['Content-Type'] = 'text/csv'
response.headers['Content-Disposition'] =
'attachment; filename="report.csv"'
User.find_each do |user|
response.stream.write "#{user.id},#{user.name},#{user.email}\n"
end
ensure
response.stream.close
end
def events
response.headers['Content-Type'] = 'text/event-stream'
response.headers['Cache-Control'] = 'no-cache'
10.times do |i|
response.stream.write "data: #{i}\n\n"
sleep 1
end
ensure
response.stream.close
end
end
Best Practices
- Follow REST conventions - Use standard CRUD actions when possible
- Keep controllers thin - Move business logic to models/services
- Use strong parameters - Always sanitize input parameters
- Handle errors gracefully - Implement proper error handling
- Use before_action - DRY up common operations with filters
- Return proper status codes - Use semantic HTTP status codes
- Implement proper authentication - Secure your controllers
- Use respond_to for multiple formats - Support HTML, JSON, etc.
- Leverage flash messages - Provide user feedback
- Version your APIs - Use namespacing for API versions
Common Pitfalls
- Fat controllers - Putting too much logic in controllers
- Missing CSRF protection - Not using authenticity tokens
- Weak parameters - Permitting too many or wrong parameters
- No error handling - Not rescuing exceptions
- Missing authorization - Not checking user permissions
- Inconsistent responses - Different status codes for same scenarios
- Session bloat - Storing too much data in session
- Missing before_action - Duplicating code across actions
- Incorrect redirects - Redirecting when rendering is needed
- No rate limiting - APIs without throttling
When to Use
- Building web applications with Rails
- Creating RESTful APIs
- Implementing MVC pattern
- Handling HTTP requests and responses
- Building admin interfaces
- Creating CRUD interfaces
- Implementing authentication flows
- Building multi-tenant applications
- Creating webhooks and callbacks
- Developing content management systems
Resources