Ruby on Railsのベストプラクティス
Railsアプリケーションの品質を向上させるためのベストプラクティスをまとめました。
コードの構造化
1. Fat ModelよりもService Object
# Bad
class User < ApplicationRecord
def send_welcome_email_and_create_profile
# 複雑な処理...
end
end
# Good
class UserRegistrationService
def initialize(user)
@user = user
end
def call
send_welcome_email
create_profile
end
private
def send_welcome_email
# メール送信処理
end
def create_profile
# プロフィール作成処理
end
end
2. 適切なバリデーション
class Article < ApplicationRecord
validates :title, presence: true, length: { maximum: 255 }
validates :body, presence: true
validates :author, presence: true
validates :summary, length: { maximum: 500 }
end
データベース設計
インデックスの活用
class AddIndexToArticles < ActiveRecord::Migration[8.0]
def change
add_index :articles, :created_at
add_index :articles, [:author, :draft]
end
end
N+1問題の回避
# Bad
articles = Article.all
articles.each { |article| puts article.comments.count }
# Good
articles = Article.includes(:comments)
articles.each { |article| puts article.comments.count }
セキュリティ
1. Strong Parameters
def article_params
params.require(:article).permit(:title, :body, :summary)
end
2. CSRF対策
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
end
テスト
1. 適切なテストカバレッジ
- モデルテスト: バリデーション、メソッドの動作
- コントローラーテスト: HTTPレスポンス、認証
- システムテスト: ユーザーの操作フロー
2. ファクトリーの活用
FactoryBot.define do
factory :article do
title { "Sample Article" }
body { "Sample body content" }
author { "test_user" }
draft { false }
end
end
これらのベストプラクティスを実践することで、保守性の高いRailsアプリケーションを構築できます。