Skip to the workspace
Pebellslearn by building
Controllers  ›  Lesson

Strong Parameters

(Strong) Parameters 15 minForm data arrives in params, and strong parameters make you name exactly which fields a model may receive, so users cannot set attributes you did not intend.

ruby on rails / Strong Parameters

Explore each scene at your own pace.

01 · The rule

The rule

Strong Parameters

When a member submits the "new book" form, Rails collects every field into params. It is tempting to hand the whole thing to the model. But anyone can add extra fields to a request with their browser's developer tools, and a model will happily set any attribute it is given. Strong parameters close that door.

The rule

params is untrusted: permit by name, pass only what you permit.

params holds everything from the URL, the query string and the form body. A form built for a book nests its fields under book:

# params for POST /books
{ "book" => { "title" => "Dune", "pages" => "412", "featured" => "true" },
  "controller" => "books", "action" => "create" }

Passing params[:book] straight to Book.new raises ActiveModel::ForbiddenAttributesError. You must say which keys are allowed:

class BooksController < ApplicationController
  def create
    @book = Book.new(book_params)
    # ...
  end

  private

  def book_params
    params.expect(book: [:title, :author, :pages])          # Rails 8
    # params.require(:book).permit(:title, :author, :pages) # Rails 7 style, still works
  end
end
  • require(:book) / expect(book: ...) — the book key must be present, or Rails answers 400 Bad Request.
  • The listed fields are kept; anything else (here featured) is dropped.

Arrays and nested hashes need their shape spelled out: genre_ids: [] for a list of ids, or address: [:city, :zip] for a nested hash.

Values in params are always strings ("412"). The model converts them to the column's type when it assigns them.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.