--- name: action-controller description: Expert guidance for writing Rails controllers with Action Controller. Use when writing controller actions, strong parameters, before_action filters, rendering responses, redirects, flash messages, sessions, cookies, rescue_from error handling, streaming, CSRF protection, or HTTP authentication. Covers params permitting (especially nested params — the #1 source of agent bugs), callbacks, request/response objects, and security. Trigger on "controller", "action", "strong parameters", "params", "before_action", "redirect", "render", "flash", "session", "cookies", "rescue_from", "CSRF", "permit", "expect", "filters", "callbacks". allowed-tools: Read, Grep, Glob, Write, Edit, Bash(bin/rails generate controller*), Bash(bin/rails routes*) --- # Rails Action Controller Expert Write correct, secure, and idiomatic Rails controllers following Rails 8.1 conventions. ## Philosophy 1. **Thin controllers** — Business logic belongs in models/services, not controllers 2. **Strong parameters protect against mass assignment** — Raw params let attackers set any attribute (admin flags, user IDs, etc.) 3. **Convention over configuration** — Follow RESTful patterns; fight the urge to add custom actions 4. **Fail secure** — Default to restricting access, then open up selectively 5. **One controller, one resource** — If your controller handles two resources, split it ## When To Use This Skill - Writing new controller actions (CRUD or custom) - Permitting parameters (especially nested hashes/arrays — this is where bugs live) - Adding before_action filters for auth/authorization - Setting up rescue_from for error handling - Working with sessions, cookies, or flash messages - Rendering responses or redirecting - Implementing streaming or file downloads - Configuring CSRF protection or HTTP auth ## Instructions ### Step 1: Check Existing Patterns **Look at the project's existing controllers first** — consistency with the codebase matters more than textbook patterns: ```bash # See what ApplicationController provides cat app/controllers/application_controller.rb # Find similar controllers ls app/controllers/ # Check for shared concerns ls app/controllers/concerns/ # Check routes for the resource bin/rails routes | grep resource_name ``` Consistency beats "best practice." ### Step 2: Controller Structure Follow this ordering inside every controller: ```ruby class ArticlesController < ApplicationController # 1. Includes/concerns include Searchable # 2. Constants (if any) ITEMS_PER_PAGE = 25 # 3. Callbacks — order matters, they run top-to-bottom before_action :authenticate_user! before_action :set_article, only: [:show, :edit, :update, :destroy] before_action :authorize_article, only: [:edit, :update, :destroy] # 4. Public actions (RESTful order: index, show, new, create, edit, update, destroy) def index @articles = Article.all end def show; end def new @article = Article.new end def create @article = Article.new(article_params) if @article.save redirect_to @article, notice: "Article created." else render :new, status: :unprocessable_entity end end def edit; end def update if @article.update(article_params) redirect_to @article, notice: "Article updated." else render :edit, status: :unprocessable_entity end end def destroy @article.destroy! redirect_to articles_path, notice: "Article deleted.", status: :see_other end # 5. Private methods private def set_article @article = Article.find(params.expect(:id)) end def authorize_article redirect_to articles_path, alert: "Not authorized." unless @article.user == current_user end def article_params params.expect(article: [:title, :body, :published]) end end ``` ### Step 3: Strong Parameters This is where most controller bugs come from — especially with nested hashes and arrays. #### Use `expect` (Rails 8+) Over `require` + `permit` ```ruby # ✅ Rails 8+ — prefer expect (combines require + permit) def article_params params.expect(article: [:title, :body, :published]) end # ⚠️ Older style — still works but expect is preferred def article_params params.require(:article).permit(:title, :body, :published) end ``` #### Nested Hashes — The Danger Zone ```ruby # Nested hash (belongs_to address, has fields) # Form sends: { user: { name: "Jo", address: { street: "123 Main", city: "NY" } } } def user_params params.expect(user: [:name, address: [:street, :city, :zip]]) end # ⚠️ Wrong — this permits NOTHING inside address def user_params params.expect(user: [:name, :address]) # address is a hash, not a scalar! end ``` #### Arrays of Scalars ```ruby # Array of simple values: { article: { title: "Hi", tag_ids: [1, 2, 3] } } def article_params params.expect(article: [:title, tag_ids: []]) end ``` #### Arrays of Hashes (accepts_nested_attributes_for) ```ruby # Array of nested objects — NOTE THE DOUBLE ARRAY SYNTAX [[...]] # { project: { name: "X", tasks_attributes: [{ title: "A" }, { title: "B" }] } } def project_params params.expect(project: [:name, tasks_attributes: [[:title, :done, :id, :_destroy]]]) end ``` **Double array `[[...]]`** = "I expect an array of hashes, each with these keys." This is the Rails 8 `expect` syntax. Agents get this wrong constantly. #### Arbitrary Hash (Use Sparingly) ```ruby # When you genuinely can't enumerate keys (e.g., JSON metadata blob) def product_params params.expect(product: [:name, metadata: {}]) end # ⚠️ metadata: {} permits ANY keys — only use when truly dynamic ``` #### Common Gotchas | Bug | Fix | |-----|-----| | `permit(:tags)` when tags is an array | `permit(tags: [])` | | `permit(:address)` when address is a hash | `permit(address: [:street, :city])` | | `permit(:images)` for file uploads | `permit(images: [])` for multiple files | | Nested attributes without `_destroy` and `id` | `permit(items_attributes: [[:name, :id, :_destroy]])` | | Using `permit!` to "just make it work" | Enumerate your params — `permit!` allows attackers to set any attribute | ### Step 4: Callbacks (before_action, after_action, around_action) #### before_action ```ruby class PostsController < ApplicationController before_action :authenticate_user! before_action :set_post, only: [:show, :edit, :update, :destroy] # Skip inherited callbacks selectively skip_before_action :authenticate_user!, only: [:index, :show] private def set_post @post = Post.find(params.expect(:id)) end end ``` **Key rules:** - Callbacks run in declaration order — put auth before resource loading - A callback that renders or redirects **halts the chain** (remaining callbacks and the action won't run) - Use `only:` / `except:` to scope callbacks to specific actions - `skip_before_action` only works for callbacks inherited from parent classes or registered earlier #### around_action ```ruby around_action :wrap_in_transaction, only: [:create, :update] private def wrap_in_transaction ActiveRecord::Base.transaction do yield # executes the action end end ``` **The `yield` is required** — without it the action never executes. ### Step 5: Rendering Responses ```ruby # Implicit render — renders app/views/posts/index.html.erb def index @posts = Post.all # no explicit render needed end # Explicit render of a different template render :new # same controller, different action template render "posts/new" # cross-controller template render plain: "OK" # plain text render json: @post # JSON render json: @post, status: :created # JSON with status render html: "