Rails Expert

作者 jeffallan1be15d8064f8MIT11K 個星標收錄於 2026年10月8日更新於 2026年10月8日儲存庫5 天前更新

Rails 7+ specialist that optimizes Active Record queries with includes/eager_load, implements Turbo Frames and Turbo Streams for partial page updates, configures Action Cable for WebSocket connections, sets up Sidekiq workers for background job processing, and writes comprehensive RSpec test suites. Use when building Rails 7+ web applications with Hotwire, real-time features, or background job processing. Invoke for Active Record optimization, Turbo Frames/Streams, Action Cable, Sidekiq, RSpec Rails.

AI 產生的概覽

指導 Rails 7+ 實作:Active Record 最佳化、Hotwire/Turbo、Action Cable、Sidekiq 工作與 RSpec 測試。

功能
此技能為建置 Rails 7+ 網頁應用程式提供實作指引。內容涵蓋以 includes/eager_load 最佳化 Active Record 查詢、用 Turbo Frames 與 Turbo Streams 進行局部頁面更新、設定 Action Cable WebSocket、撰寫 Sidekiq 背景工作,以及撰寫 RSpec 測試套件。它也包含關於 API 開發與測試的參考文件,以及遷移、模型、控制器、檢視與測試的程式碼範本。
適用情境
適用於建置或擴充 Rails 7+ 應用程式,尤其是涉及 Hotwire、即時功能、背景工作處理,或需要最佳化 Active Record 查詢與撰寫 RSpec 測試的情境。
執行需求
不含指令碼,僅為指示與參考文件。假定工作環境中已有 Rails 7+ 專案,並具備 Ruby、Bundler、RSpec、RuboCop、Sidekiq 與 Hotwire/Turbo。

Rails Expert

Core Workflow

  1. Analyze requirements — Identify models, routes, real-time needs, background jobs
  2. Scaffold resources — rails generate model User name:string email:string, rails generate controller Users
  3. Run migrations — rails db:migrate and verify schema with rails db:schema:dump
    • If migration fails: inspect db/schema.rb for conflicts, rollback with rails db:rollback, fix and retry
  4. Implement — Write controllers, models, add Hotwire (see Reference Guide below)
  5. Validate — bundle exec rspec must pass; bundle exec rubocop for style
    • If specs fail: check error output, fix failing examples, re-run with --format documentation for detail
    • If N+1 queries surface during review: add includes/eager_load (see Common Patterns) and re-run specs
  6. Optimize — Audit for N+1 queries, add missing indexes, add caching

Reference Guide

Load detailed guidance based on context:

TopicReferenceLoad When
Hotwire/Turboreferences/hotwire-turbo.mdTurbo Frames, Streams, Stimulus controllers
Active Recordreferences/active-record.mdModels, associations, queries, performance
Background Jobsreferences/background-jobs.mdSidekiq, job design, queues, error handling
Testingreferences/rspec-testing.mdModel/request/system specs, factories
API Developmentreferences/api-development.mdAPI-only mode, serialization, authentication

Common Patterns

N+1 Prevention with includes/eager_load

ruby
# BAD — triggers N+1posts = Post.allposts.each { |post| puts post.author.name }
# GOOD — eager load associationposts = Post.includes(:author).allposts.each { |post| puts post.author.name }
# GOOD — eager_load forces a JOIN (useful when filtering on association)posts = Post.eager_load(:author).where(authors: { verified: true })

Turbo Frame Setup (partial page update)

erb
<%# app/views/posts/index.html.erb %><%= turbo_frame_tag "posts" do %>  <%= render @posts %>  <%= link_to "Load More", posts_path(page: @next_page) %><% end %>
<%# app/views/posts/_post.html.erb %><%= turbo_frame_tag dom_id(post) do %>  <h2><%= post.title %></h2>  <%= link_to "Edit", edit_post_path(post) %><% end %>
ruby
# app/controllers/posts_controller.rbdef index  @posts = Post.includes(:author).page(params[:page])  @next_page = @posts.next_pageend

Sidekiq Worker Template

ruby
# app/jobs/send_welcome_email_job.rbclass SendWelcomeEmailJob < ApplicationJob  queue_as :default  sidekiq_options retry: 3, dead: false
  def perform(user_id)    user = User.find(user_id)    UserMailer.welcome(user).deliver_now  rescue ActiveRecord::RecordNotFound => e    Rails.logger.warn("SendWelcomeEmailJob: user #{user_id} not found — #{e.message}")    # Do not re-raise; record is gone, no point retrying  endend
# Enqueue from controller or model callbackSendWelcomeEmailJob.perform_later(user.id)

Strong Parameters (controller template)

ruby
# app/controllers/posts_controller.rbclass PostsController < ApplicationController  before_action :set_post, only: %i[show edit update destroy]
  def create    @post = Post.new(post_params)    if @post.save      redirect_to @post, notice: "Post created."    else      render :new, status: :unprocessable_entity    end  end
  private
  def set_post    @post = Post.find(params[:id])  end
  def post_params    params.require(:post).permit(:title, :body, :published_at)  endend

Constraints

MUST DO

  • Prevent N+1 queries with includes/eager_load on every collection query involving associations
  • Write comprehensive specs targeting >95% coverage
  • Use service objects for complex business logic; keep controllers thin
  • Add database indexes for every column used in WHERE, ORDER BY, or JOIN
  • Offload slow operations to Sidekiq — never run them synchronously in a request cycle

MUST NOT DO

  • Skip migrations for schema changes
  • Use raw SQL without sanitization (sanitize_sql or parameterized queries only)
  • Expose internal IDs in URLs without consideration

Output Templates

When implementing Rails features, provide:

  1. Migration file (if schema changes needed)
  2. Model file with associations and validations
  3. Controller with RESTful actions and strong parameters
  4. View files or Hotwire setup
  5. Spec files for models and requests
  6. Brief explanation of architectural decisions

Maintained by @jeffallan, Principal Consultant at Synergetic Solutions

Documentation

來源與署名

來源:jeffallan/claude-skills位於skills/rails-expert提交1be15d8

授權條款: MIT

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架