ruby-rails-best-practices
Apply Ruby on Rails best practices for MVC architecture, Active Record patterns, and convention over configuration. Use for building Rails applications and APIs.
Works with
---
name: ruby-rails-best-practices
description: Apply Ruby on Rails best practices for MVC architecture, Active Record patterns, and convention over configuration. Use for building Rails applications and APIs.
license: MIT
---
# Ruby on Rails Best Practices
Master Rails conventions and best practices for building maintainable Ruby on Rails applications.
## When to Use This Skill
- Building Rails web applications
- Creating Rails APIs
- Optimizing Rails performance
- Following Rails conventions
- Code reviews for Rails projects
## Core Patterns
### RESTful Controllers
```ruby
class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
def index
@users = User.page(params[:page])
end
def show
end
def create
@user = User.new(user_params)
if @user.save
redirect_to @user, notice: 'User created successfully'
else
render :new
end
end
private
def set_user
@user = User.find(params[:id])
end
def user_params
params.require(:user).permit(:name, :email)
end
end
```
### Active Record Best Practices
```ruby
# Scopes
class User < ApplicationRecord
scope :active, -> { where(active: true) }
scope :recent, -> { where('created_at > ?', 1.week.ago) }
# Validations
validates :email, presence: true, uniqueness: true, format: { with: URI::MailTo::EMAIL_REGEXP }
validates :age, numericality: { greater_than: 0 }
# Associations
has_many :posts, dependent: :destroy
has_many :comments, through: :posts
# Callbacks
before_save :normalize_email
private
def normalize_email
self.email = email.downcase.strip
end
end
```
### Service Objects
```ruby
# app/services/user_registration_service.rb
class UserRegistrationService
def initialize(user_params)
@user_params = user_params
end
def call
User.transaction do
user = User.create!(@user_params)
send_welcome_email(user)
track_registration(user)
user
end
rescue ActiveRecord::RecordInvalid => e
{ success: false, error: e.message }
end
private
def send_welcome_email(user)
UserMailer.welcome(user).deliver_later
end
def track_registration(user)
Analytics.track(event: 'user_registered', user_id: user.id)
end
end
```
### Background Jobs
```ruby
class ProcessUploadJob < ApplicationJob
queue_as :default
retry_on NetworkError, wait: 5.seconds, attempts: 3
def perform(upload_id)
upload = Upload.find(upload_id)
upload.process!
end
end
# Usage
ProcessUploadJob.perform_later(upload.id)
```
### Testing with RSpec
```ruby
RSpec.describe User, type: :model do
describe 'validations' do
it { should validate_presence_of(:email) }
it { should validate_uniqueness_of(:email) }
end
describe 'associations' do
it { should have_many(:posts) }
end
describe '#active?' do
it 'returns true for active users' do
user = create(:user, active: true)
expect(user.active?).to be true
end
end
end
# Controller spec
RSpec.describe UsersController, type: :controller do
describe 'GET #index' do
it 'returns a success response' do
get :index
expect(response).to be_successful
end
end
end
```
### Performance Optimization
```ruby
# N+1 query prevention
users = User.includes(:posts).all
# Counter cache
class Post < ApplicationRecord
belongs_to :user, counter_cache: true
end
# Fragment caching
<% cache @product do %>
<%= render @product %>
<% end %>
# Database indexing
class AddIndexToUsersEmail < ActiveRecord::Migration[7.0]
def change
add_index :users, :email, unique: true
end
end
```
### Security
```ruby
# Strong parameters
def user_params
params.require(:user).permit(:name, :email)
end
# Authentication
class ApplicationController < ActionController::Base
before_action :authenticate_user!
end
# Authorization with Pundit
class PostPolicy < ApplicationPolicy
def update?
user.admin? || record.user == user
end
end
```
## Resources
- Rails Guides
- Ruby Style Guide
- RailsCasts / GoRailsMore Backend Frameworks skills
git-guardrails-claude-code
mattpocock/skills
Set up Claude Code hooks to block dangerous git commands (push, reset --hard, clean, branch -D, etc.) before they execute. Use when user wants to prevent destructive git operations, add git safety hooks, or block git push/reset in Claude Code.
azure-compute
microsoft/azure-skills
Azure VM/VMSS router. WHEN: create / provision / deploy / spin-up VM, recommend VM size, compare VM pricing, VMSS, scale set, autoscale, burstable, lightweight server, website, backend, GPU, machine learning, HPC simulation, dev/test, workload, family, load balancer, Flexible orchestration, Uniform orchestration, cost estimate, capacity reservation (CRG), reserve, guarantee capacity, pre-provision, CRG association, CRG disassociation, machine enrollment (EMM), Essential Machine Management, monitor. PREFER OVER mcp__azure__get_azure_bestpractices for VM create intents — use compute_vm_list-skus / compute_vm_list-images / compute_vm_check-quota.
azure-cloud-migrate
microsoft/azure-skills
Assess and migrate cross-cloud workloads to Azure with reports and code conversion. Supports Lambda→Functions, Beanstalk/Heroku/App Engine→App Service, Fargate/Kubernetes/Cloud Run/Spring Boot→Container Apps. WHEN: migrate Lambda to Functions, AWS to Azure, migrate Beanstalk, migrate Heroku, migrate App Engine, Cloud Run migration, Fargate to ACA, ECS/Kubernetes/GKE/EKS to Container Apps, Spring Boot to Container Apps, cross-cloud migration.

