2

I'm hitting some inconsistent behavior while trying to upgrade my project to Rails 4 from 3.2 incrementally with the strong_parameters gem.

In config/application.rb I have the following:

config.active_record.whitelist_attributes = false
config.action_controller.action_on_unpermitted_parameters = :raise

I'm following the upgrade procedures as spelled out on the gem's github page.

I take a model, strip out attr_accessible and attr_protected, and add include ActiveModel::ForbiddenAttributesProtection as the first line in the class definition. Then I run rspec to find what tests are red to try to turn them green.

Class Bar

class Bar < ActiveRecord::Base
  include ActiveModel::ForbiddenAttributesProtection
  ...
end

let(:bar)  { Bar.create(type: "#{klass_name}") }

and

let(:bar)  {
  raw_params = { type: "#{klass_name}" }
  params = ActionController::Parameters.new(raw_params)
  Bar.create(params.permit(:type))
}

both produce

 ActiveModel::MassAssignmentSecurity::Error:
   Can't mass-assign protected attributes: type

regardless of the value of config.active_record.whitelist_attributes

Problem: This isn't working at all.

Class Foo

class Foo < Bar
  ...
end

For both

before :each do
  Foo.create(status: 'active')
end

and

before :each do
  raw_params = { status: 'active' }
  params = ActionController::Parameters.new(raw_params)
  Foo.create(params.permit(:status))
end

When config.active_record.whitelist_attributes = false, both turn tests green, and removing .permit(:status) correctly produces

 Failure/Error: Foo.create(params)
 ActiveModel::ForbiddenAttributes:
   ActiveModel::ForbiddenAttributes

When config.active_record.whitelist_attributes = true, both produce

Failure/Error: Foo.create(params.permit(:status))
     ActiveModel::MassAssignmentSecurity::Error:
      Can't mass-assign protected attributes: status

Problem: Either both succeed or both fail for either value of whitelist_attributes. For the purposes of iterative testing, I want a situation where traditional mass assignment fails and the updated code succeeds.

Where am I faltering?

sixtimes
  • 337
  • 2
  • 11

1 Answers1

0

Firstly, if you are upgrading to Rails 4 and using strong_parameters gem, you should have

config.active_record.whitelist_attributes = false

and

ActiveRecord::Base.send(:include, ActiveModel::ForbiddenAttributesProtection)

Secondly, it seems that 'type' is reserved for Rails https://github.com/rails/strong_parameters/issues/142, so that's why it's still giving errors even when you have permitted that type key.

My solution is to set the type through setter method like bar.type = 'YourType' when you're about to save it. That will work with no problem.

I hope it'll help.

Anh Nguyen
  • 1,202
  • 14
  • 17