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
endrequire(:book)/expect(book: ...)— thebookkey must be present, or Rails answers400 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.