Rails Expert
Core Workflow
- Analyze requirements — Identify models, routes, real-time needs, background jobs
- Scaffold resources —
rails generate model User name:string email:string, rails generate controller Users
- 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
- Implement — Write controllers, models, add Hotwire (see Reference Guide below)
- 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
- Optimize — Audit for N+1 queries, add missing indexes, add caching
Reference Guide
Load detailed guidance based on context:
| Topic |
Reference |
Load When |
| Hotwire/Turbo |
references/hotwire-turbo.md |
Turbo Frames, Streams, Stimulus controllers |
| Active Record |
references/active-record.md |
Models, associations, queries, performance |
| Background Jobs |
references/background-jobs.md |
Sidekiq, job design, queues, error handling |
| Testing |
references/rspec-testing.md |
Model/request/system specs, factories |
| API Development |
references/api-development.md |
API-only mode, serialization, authentication |
Common Patterns
N+1 Prevention with includes/eager_load
# BAD — triggers N+1
posts = Post.all
posts.each { |post| puts post.author.name }
# GOOD — eager load association
posts = Post.includes(:author).all
posts.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)
<%# 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 %>
# app/controllers/posts_controller.rb
def index
@posts = Post.includes(:author).page(params[:page])
@next_page = @posts.next_page
end
Sidekiq Worker Template
# app/jobs/send_welcome_email_job.rb
class 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
end
end
# Enqueue from controller or model callback
SendWelcomeEmailJob.perform_later(user.id)
Strong Parameters (controller template)
# app/controllers/posts_controller.rb
class 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)
end
end
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:
- Migration file (if schema changes needed)
- Model file with associations and validations
- Controller with RESTful actions and strong parameters
- View files or Hotwire setup
- Spec files for models and requests
- Brief explanation of architectural decisions
1---2name: rails-expert3description: 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.4license: MIT5---67# Rails Expert89## Core Workflow10111. **Analyze requirements** — Identify models, routes, real-time needs, background jobs122. **Scaffold resources** — `rails generate model User name:string email:string`, `rails generate controller Users`133. **Run migrations** — `rails db:migrate` and verify schema with `rails db:schema:dump`14 - If migration fails: inspect `db/schema.rb` for conflicts, rollback with `rails db:rollback`, fix and retry154. **Implement** — Write controllers, models, add Hotwire (see Reference Guide below)165. **Validate** — `bundle exec rspec` must pass; `bundle exec rubocop` for style17 - If specs fail: check error output, fix failing examples, re-run with `--format documentation` for detail18 - If N+1 queries surface during review: add `includes`/`eager_load` (see Common Patterns) and re-run specs196. **Optimize** — Audit for N+1 queries, add missing indexes, add caching2021## Reference Guide2223Load detailed guidance based on context:2425| Topic | Reference | Load When |26|-------|-----------|-----------|27| Hotwire/Turbo | `references/hotwire-turbo.md` | Turbo Frames, Streams, Stimulus controllers |28| Active Record | `references/active-record.md` | Models, associations, queries, performance |29| Background Jobs | `references/background-jobs.md` | Sidekiq, job design, queues, error handling |30| Testing | `references/rspec-testing.md` | Model/request/system specs, factories |31| API Development | `references/api-development.md` | API-only mode, serialization, authentication |3233## Common Patterns3435### N+1 Prevention with includes/eager_load3637```ruby38# BAD — triggers N+139posts = Post.all40posts.each { |post| puts post.author.name }4142# GOOD — eager load association43posts = Post.includes(:author).all44posts.each { |post| puts post.author.name }4546# GOOD — eager_load forces a JOIN (useful when filtering on association)47posts = Post.eager_load(:author).where(authors: { verified: true })48```4950### Turbo Frame Setup (partial page update)5152```erb53<%# app/views/posts/index.html.erb %>54<%= turbo_frame_tag "posts" do %>55 <%= render @posts %>56 <%= link_to "Load More", posts_path(page: @next_page) %>57<% end %>5859<%# app/views/posts/_post.html.erb %>60<%= turbo_frame_tag dom_id(post) do %>61 <h2><%= post.title %></h2>62 <%= link_to "Edit", edit_post_path(post) %>63<% end %>64```6566```ruby67# app/controllers/posts_controller.rb68def index69 @posts = Post.includes(:author).page(params[:page])70 @next_page = @posts.next_page71end72```7374### Sidekiq Worker Template7576```ruby77# app/jobs/send_welcome_email_job.rb78class SendWelcomeEmailJob < ApplicationJob79 queue_as :default80 sidekiq_options retry: 3, dead: false8182 def perform(user_id)83 user = User.find(user_id)84 UserMailer.welcome(user).deliver_now85 rescue ActiveRecord::RecordNotFound => e86 Rails.logger.warn("SendWelcomeEmailJob: user #{user_id} not found — #{e.message}")87 # Do not re-raise; record is gone, no point retrying88 end89end9091# Enqueue from controller or model callback92SendWelcomeEmailJob.perform_later(user.id)93```9495### Strong Parameters (controller template)9697```ruby98# app/controllers/posts_controller.rb99class PostsController < ApplicationController100 before_action :set_post, only: %i[show edit update destroy]101102 def create103 @post = Post.new(post_params)104 if @post.save105 redirect_to @post, notice: "Post created."106 else107 render :new, status: :unprocessable_entity108 end109 end110111 private112113 def set_post114 @post = Post.find(params[:id])115 end116117 def post_params118 params.require(:post).permit(:title, :body, :published_at)119 end120end121```122123## Constraints124125### MUST DO126- Prevent N+1 queries with `includes`/`eager_load` on every collection query involving associations127- Write comprehensive specs targeting >95% coverage128- Use service objects for complex business logic; keep controllers thin129- Add database indexes for every column used in `WHERE`, `ORDER BY`, or `JOIN`130- Offload slow operations to Sidekiq — never run them synchronously in a request cycle131132### MUST NOT DO133- Skip migrations for schema changes134- Use raw SQL without sanitization (`sanitize_sql` or parameterized queries only)135- Expose internal IDs in URLs without consideration136137## Output Templates138139When implementing Rails features, provide:1401. Migration file (if schema changes needed)1412. Model file with associations and validations1423. Controller with RESTful actions and strong parameters1434. View files or Hotwire setup1445. Spec files for models and requests1456. Brief explanation of architectural decisions