LearnRails 4 Strong Parameters

Jason Seifer
writes on November 7, 2012

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" />
</form>

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
end

Then in the controller:

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

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 = User.new(user_params)
    ....
  end

  private
  def user_params
    params.require(:user).permit(:name)
  end
end

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.

One Response to “Rails 4 Strong Parameters”

  1. Hey Jason, I was using rails 4 on the treebook app, had a question about strong_parameters and devise. Did I do this right? https://teamtreehouse.com/forum/strongparameters-and-treebook

Leave a Reply

You must be logged in to post a comment.

Want to learn more about Ruby?

Ruby is a dynamic, open source programming language with a focus on simplicity and productivity. Learn how to build a website using Ruby and the Rails framework.

Learn more