Site icon Treehouse Blog

Rails 4 Strong Parameters

The Rails core team recently introduced a project called strong parameters.

Strong parameters is the latest tool in the fight against mass assignment vulnerabilities. Let’s take the problem of your typical web form that creates a user. Your code might look something like this:

<form method="post" action="/users">
  <input type="text" name="name" />
  <input type="submit" />

This looks all well and good but what happens if a use messes with your form and adds another parameter in that they’re not supposed to? As an example, perhaps they add in an admin attribute and set it to true. If you aren’t protecting this in your models, you can run in to issues. Typically, you would do something like this:

class User < ActiveRecord::Base
  attr_accessible :name

Then in the controller:

def create
  @user =[:user])
  @user.admin = params[:user][:admin] # If you want this set!

In Rails 4, there’s a new option to mark parameters as safe or required. This comes in the form of a plugin called strong parameters. The way it works is like this:

class UsersController < ActionController::Base

  def create
    @user =

  def user_params

If you don’t use the correct params, an ActiveModel::ForbiddenAttributes exception is raised due to mass assignment being allowed.

If you want to check this out now, you can use it in your Rails 3.2.X applications by adding the strong_parameters gem to your Gemfile. It will be on by default in Rails 4.

Exit mobile version