The buzz cut

Ramblings from the barbershop

Upgrading to Rails4: Strong Parameters

| Comments

This is another post in a long series of Rails4 upgrades. At this point, I have a working Rails4 app that’s using all of the backward comptability gems. This post will be on removing the ‘protected_attributes’ gem and updating my code to use Rails 4’s strong parameters logic

As you likely know, Rails 4 changed how we protect our apps from mass assignment vulnerabilities. Previously we used “attr_accessor” in the model, but with Rails 4, we should use strong_parameters in the controller. The protected_attributes gem provides backward compatability, allowing attr_accessor to still work, but who wants to live in the past?

I went through all of my models and made changes like this:

1
2
3
4
5
6
7
8
9
10
# Plan.rb

# We no longer need the following line. Delete it
# attr_accessible :name, :description

# The next line is temporary. It allows us to change
# one model at a time before removing the protected_attributes
# gem completely. Remove it when all models/controllers
# have been updated.
include ActiveModel::ForbiddenAttributesProtection

Then I tweaked the corresponding controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# PlansController

def create
  ...
  # @plan = Plan.new(params[:plan]) ## remove this line
  @plan = Plan.new(plan_params)
  ...
end

def update
  ...
  # if @plan.update_attributes(params[:plan]) ## remove this line
  if @plan.update_attributes(plan_params)
  ...
end

def plan_params
  params.require(:plan).permit(:name, :description)
end

Once I had tested all of my changes, I removed the protected_attributes gem and removed the “include ActiveModel::ForbiddenAttributesProtection” from all of my models.

One down!

Comments