Sitemap
Pedro Henrique Altoé

Pedro Henrique Altoé

Forms Part 2 — Strong Parameters

2 min readJul 9, 2016

What are Strong Parameters?

We can call it a “Parameters Whitelist”. Before an attribute gets passed into the Model, they have to be “permitted”. When you pass an attribute that is not explicitly permitted, it will throw a:

ActiveModel::ForbiddenAttributesError

Basically, what it does is check if the given parameter is in the allowed list, if it is, assigns it, otherwise, it throws an error.

class PostsController < ApplicationController
private
# Never trust parameters from the scary internet, only allow the white list through.
def post_params
params.require(:post).permit(:name, :content, :tag_ids => [])
end
end

That way, you defined which attributes can be passed into the Model when you (Create/Update).

So, your CREATE method would look like this:

def create
@post = Post.new(post_params)
if @post.valid?
@post.save
redirect_to post_path(@post)
else
render :new
end
end

Usually, you will want to permit the same attributes for both your CREATE and UPDATE actions.

But what happens if we, lets say, want to have control over which attributes can be used to create an object and which can be used to update?

We pass the attributes as arguments.

Get Pedro Henrique Altoé’s stories in your inbox

Join Medium for free to get updates from this writer.

So, our “post_parameters” method would look like this:

privatedef post_params(*args)
params.require(:post).permit(*args)
end

Our CREATE method would change to:

def create
@post = Post.new(post_params(*args)) # !!! You would need to pass in symbols, not the *args splat
if @post.valid?
@post.save
redirect_to post_path(@post)
else
render :new
end
end

If you wanted to “whitelist” all attributes, you could magically do this:

def post_params
params.require(:post).permit!
end

— — — -

Just to make sure, if you try to mass assign without using strong parameters, see what happens:

def create
@post = Post.new(params)
@post.save
redirect_to post_path(@post)
end
ActiveModel::ForbiddenAttributesError in ListsController#create
ActiveModel::ForbiddenAttributesError
activemodel (4.2.6) lib/active_model/forbidden_attributes_protection.rb:21:in `sanitize_for_mass_assignment’

--

--