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.

coppermare/skillverse1 installsMITSynced Aug 22

Works with

Claude CodeCursorCodex CLIGitHub CopilotGemini CLI
---
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 / GoRails

More Backend Frameworks skills

← All Backend Frameworks skills

Check your AI visibility

One URL in, a 0–100 score and the exact fixes out.

RUN THE CHECK

Browse all the tools

15 tools across six categories
13 of them never send your data anywhere

Free · No signup · No trial clock

SEE THE DIRECTORY