Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 37 ยท Routing and Controllers

Strong Parameters and Filters

Learn Rails strong parameters (require, permit, expect) to prevent mass assignment attacks, plus before_action, after_action and around_action filters and rescue_from, with runnable plain-Ruby stand-ins.

Two of the most important habits in Rails controllers are filtering input and sharing setup code. The first is called strong parameters: you decide which form fields the user may set, so an attacker cannot slip in admin=true. The second is called filters (also known as callbacks): methods that run before or after actions, so you do not repeat "find the article" or "check the login" in every action.

In this lesson you will learn how to use params.require, permit and the newer expect, how before_action and friends are used and skipped, and how rescue_from handles errors in one place. The Rails code is read-only here, and each idea has a runnable stand-in written in plain Ruby.

Mass assignment: the problem

Article.new(params[:article]) would copy every submitted field onto the model. A malicious visitor can add fields to the form:

TEXT
article[title]=Hi&article[body]=Text&article[admin]=true&article[user_id]=1

If the model has an admin or user_id column, the attacker just set it. This is called a mass assignment vulnerability. Rails closes the hole: a params object that has not been explicitly permitted raises ActiveModel::ForbiddenAttributesError when you pass it to new, create or update.

Strong parameters

You declare the allowed fields in a private method:

Ruby
# read-only
private

def article_params
  params.require(:article).permit(:title, :body, :published)
end

require(:article) demands that the key exists (otherwise a 400 Bad Request is returned) and returns the nested hash. permit(...) returns a copy containing only the listed keys. Everything else is silently dropped (and logged).

You can permit nested data too:

Ruby
# read-only
params.require(:article).permit(:title, tag_ids: [])             # array of ids
params.require(:order).permit(:note, items: [:sku, :quantity])   # array of hashes
params.require(:user).permit(address: [:street, :city])          # nested hash

Rails 8 adds expect, a stricter shortcut that also checks the shape:

Ruby
# read-only
params.expect(article: [:title, :body])     # like require + permit
params.expect(order: [[:sku, :quantity]])   # array of hashes

Use whichever your Rails version supports; the point is the same.

Never permit fields you do not want users to control: :admin, :role, :user_id, :price on an order line, and so on. Set those in the controller yourself: @article = current_user.articles.build(article_params).

Stand-in: a permit implementation

This stand-in does the core of strong parameters. It builds a new hash with only the listed keys, supports nested arrays of scalars and raises if an unpermitted object is used for assignment.

Ruby Stand-in: require and permit

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 attributes admin, user_id and role never reach the model. That is the whole security benefit in one example.

Filters: before_action, after_action, around_action

A filter is a method that Rails runs around your actions. The most common is before_action. It removes repetition:

Ruby
# read-only
class ArticlesController < ApplicationController
  before_action :require_login
  before_action :set_article, only: [:show, :edit, :update, :destroy]

  def show; end        # @article is already set
  def edit; end

  private

  def set_article
    @article = Article.find(params[:id])
  end

  def require_login
    redirect_to login_path, alert: "Please sign in" unless current_user
  end
end

Facts about filters:

  • They run in the order declared. If a before_action redirects or renders, the filter chain stops and the action never runs.
  • only: and except: restrict which actions use the filter.
  • A filter declared in ApplicationController applies to every controller. Opt out with skip_before_action :require_login, only: [:index, :show].
  • after_action runs after the action, and around_action wraps it with yield, useful for timing or per-request settings:
Ruby
# read-only
around_action :use_user_time_zone

def use_user_time_zone(&block)
  Time.use_zone(current_user.time_zone, &block)
end
flowchart TD
  A["Request"] --> B["before_action :require_login"]
  B -->|"redirected?"| X["Stop: response sent"]
  B --> C["before_action :set_article"]
  C --> D["Action runs"]
  D --> E["after_action callbacks"]
  E --> F["Response"]

A filter that renders or redirects ends the chain. Otherwise the next filter and finally the action run.

Stand-in: a filter chain

Below, filters are collected with a class macro, and process runs them in order, stopping when one responds.

Ruby Stand-in: before_action, only and skip

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.

Notice that ArticlesController inherited require_login from ApplicationController, that set_article only ran for show, and that for a guest the chain stopped before the action ran.

rescue_from: handling errors in one place

Instead of begin/rescue blocks in every action, declare handlers once:

Ruby
# read-only
class ApplicationController < ActionController::Base
  rescue_from ActiveRecord::RecordNotFound, with: :not_found
  rescue_from ActionController::ParameterMissing, with: :bad_request

  private

  def not_found
    render plain: "Not found", status: :not_found
  end

  def bad_request(error)
    render json: { error: error.message }, status: :bad_request
  end
end

Now any Article.find that fails anywhere in any controller gives a clean 404. Pair this with custom exceptions for your own error classes (for example NotAuthorized โ†’ 403).

Stand-in: rescue_from

Ruby Stand-in: central error handlers

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.

Keep filters small and named for what they do (set_article, require_login). A controller with eight filters is hard to follow; move shared logic into concerns or plain objects.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does params.require(:article).permit(:title, :body) return?

    permit returns a copy with only the listed keys; other keys are dropped.
  2. 2. What is a mass assignment vulnerability?

    Without filtering, any submitted field could be written to the model.
  3. 3. What happens if a before_action calls redirect_to?

    A render or redirect in a filter halts the chain.
  4. 4. How do you run a filter only for show and edit?

    The only: option limits which actions use the filter.

Summary

  • Strong parameters (require/permit, or expect) whitelist form fields and stop mass assignment attacks.
  • Never permit fields users must not control; set them yourself in the controller.
  • before_action, after_action and around_action share code between actions; only:, except: and skip_* control where they apply.
  • A filter that renders or redirects stops the chain.
  • rescue_from handles exceptions such as "record not found" in one place.

Next: Sessions, Cookies and Flash