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.
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