LearnRails 4 Strong Parameters

   
Avatar

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.

GET STARTED NOW

Learning with Treehouse for only 30 minutes a day can teach you the skills needed to land the job that you've been dreaming about.

Get Started

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.

man working on his laptop

Are you ready to start learning?

Learning with Treehouse for only 30 minutes a day can teach you the skills needed to land the job that you've been dreaming about.

Start a Free Trial
woman working on her laptop