Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 37 ยท Forms, Validation and Callbacks

Strong Parameters and Mass Assignment

Understand mass assignment attacks and how Rails strong parameters (require, permit, params.expect) whitelist fields, with nested arrays, unpermitted parameters and a runnable stand-in of the whitelist logic.

When a form is submitted, the browser sends a bag of keys and values, and the user controls every one of them. Anyone can open the developer tools, add a field named admin with the value true, and send it. If your controller blindly hands all submitted values to User.create(params[:user]), the visitor just made themselves an administrator. This flaw is called mass assignment, and it caused a famous break-in on a major code-hosting site in 2012.

Rails answers it with strong parameters: the controller must explicitly list which keys it accepts. Everything else is dropped. This lesson shows the API, the nested cases that confuse people, and a runnable stand-in of the logic. Real Rails code is read-only here.

The problem in one line

Ruby
# DANGEROUS if it worked: every submitted key goes straight into the model
User.create(params[:user])

Rails prevents this: params[:user] is an ActionController::Parameters object, not a plain hash. Passing it to create or update without calling permit raises ActiveModel::ForbiddenAttributesError. The error is a feature: it forces you to decide which fields are allowed.

require and permit

Ruby
class PostsController < ApplicationController
  def create
    @post = Post.new(post_params)
    # ...
  end

  private

  def post_params
    params.require(:post).permit(:title, :body, :published)
  end
end
  • require(:post) insists that the post key exists and is not empty, otherwise it raises ActionController::ParameterMissing, which Rails turns into a 400 Bad Request.
  • permit(...) returns a copy that contains only the listed keys. Any other key (admin, author_id) is silently dropped (and logged as "Unpermitted parameter" in development).

Since Rails 8.0 there is a stricter, shorter form:

Ruby
def post_params
  params.expect(post: [:title, :body, :published])
end

expect requires the shape too: if post is missing or not a hash (for example a string, or an array of hashes sent by an attacker), it responds with a 400 instead of raising an unexpected error. Prefer it in new code; require.permit remains common in older apps and guides.

Ruby Stand-in: a whitelist of parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Nested hashes, arrays and attributes

The tricky part is the syntax for structures inside the permitted list.

Ruby
params.require(:post).permit(
  :title,
  tag_ids: [],                                  # an array of scalar values
  address: [:street, :city],                     # a nested hash
  comments_attributes: [:id, :body, :_destroy]   # nested attributes (an array of hashes)
)

Rules to remember:

  • tag_ids: [] permits an array of simple values. Write it at the end of the list because keyword-style entries must come last in Ruby.
  • A hash entry (address: [...]) lists the keys allowed inside it.
  • For nested attributes, Rails submits line_items_attributes[0][name], line_items_attributes[1][name]: a hash keyed by index. permit(line_items_attributes: [:id, :name, :_destroy]) handles that shape and also arrays of hashes. Always include :id so updates modify existing rows instead of adding new ones, and :_destroy if allow_destroy: true.
  • Scalar types allowed by permit are strings, numbers, booleans, dates, nil and uploaded files. A hash or array where a scalar is permitted is rejected.

Different rules for different actions

A common design is one private method per use case, because creating and updating often allow different fields:

Ruby
def user_params
  params.expect(user: [:name, :email, :password, :password_confirmation])
end

def admin_user_params
  params.expect(user: [:name, :email, :role])
end

Never put :admin, :role, :id (on create), :user_id or :owner_id in a list that ordinary users reach. Set those on the server instead:

Ruby
@post = current_user.posts.build(post_params)   # user_id set by the association

This is better than permitting user_id, because the client can no longer choose whose post it is.

Other places params appear

Ruby
params[:id]                 # a route segment, e.g. /posts/7
params[:page]               # query string, always a string like "2"
params.fetch(:page, 1)      # with a default
params.to_unsafe_h          # escapes the protection; avoid it

Parameters arrive as strings. params[:page] is "2", not 2; Active Record casts attributes for you when assigned to a model, but you must convert values yourself elsewhere (params[:page].to_i).

JSON requests work the same way. A body of {"post": {"title": "Hi"}} with Content-Type: application/json also appears as params[:post]; with wrap_parameters enabled, even a flat JSON body gets wrapped under the controller's model name.

Ruby Stand-in: permitting arrays and nested attributes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The stand-in is simplified, but it shows the three shapes (array of scalars, nested hash, indexed nested attributes) and that unknown keys such as admin, secret and price_override vanish.

Strong parameters protect the model from unexpected keys. They do not validate values. You still need validations for that, and authorization checks to decide whether this user may edit this record.

Testing it

A request test can post an extra key and assert it was ignored:

Ruby
test "ignores admin param" do
  post users_url, params: { user: { name: "A", email: "[email protected]", admin: true } }
  assert_not User.last.admin?
end

More on request tests in testing with Minitest.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens if you pass params[:user] straight to User.create without permit?

    Unpermitted Parameters objects cannot be mass-assigned; Rails raises ForbiddenAttributesError.
  2. 2. How do you permit an array of ids named tag_ids?

    An empty array value means: an array of permitted scalar values.
  3. 3. What does params.expect(post: [:title]) add over require(:post).permit(:title)?

    expect (Rails 8) checks both presence and shape and answers 400 Bad Request for malformed input.
  4. 4. Why use current_user.posts.build(post_params) instead of permitting :user_id?

    Building through the association sets the foreign key from trusted server state.

Summary

  • Mass assignment lets users set fields you never meant to expose; strong parameters whitelist keys.
  • params.require(:model).permit(...) and Rails 8 params.expect(model: [...]) return the safe subset.
  • Arrays are key: []; nested hashes and attributes use key: [...]; include :id and :_destroy for nested updates.
  • Set ownership and roles on the server, never from params.
  • Params are strings; strong parameters do not validate or authorize.

Next: Validations