Jon Snow
Jon Snow

Reputation: 11892

Can you use strong parameters and whitelist attributes together in Rails 3?

We're on Rails 3. We'd like to switch to strong parameters through the strong_parameters gem.

The documentation of the gem says that to use this gem, the following value needs to be changed from true to false in the config/application.rb file

config.active_record.whitelist_attributes = false

We have many models and controllers in our application. Making this change means we have to migrate ALL our models and controllers to strong parameters?

Ideally we'd like to migrate gradually. That is, start using strong parameters for the new models and controllers, and then gradually update all the models and controllers.

So can you use strong parameters for some models/controllers and whitelist attributes for others?

Thank you.

Upvotes: 2

Views: 1395

Answers (2)

Scott Jacobsen
Scott Jacobsen

Reputation: 985

I just started doing this. My experience is that I can leave the auto-whitelist enabled:

config.active_record.whitelist_attributes = true

Then I need to explicitly disable the whitelist in models I'm migrating to strong params using attr_protected:

class Widget < ActiveRecord::Base
  attr_protected # disable whitelist in this model
  include ActiveModel::ForbiddenAttributesProtection
  ...
end

Upvotes: 3

Bart Jedrocha
Bart Jedrocha

Reputation: 11570

Yes you can use both together. You can simply mixin the ActiveModel::ForbiddenAttributesProtection module to the models you want to migrate to strong parameters while keeping your whitelist via attr_accessible in other models. Just don't disable the whitelist default until you've made the complete cutover. In other words, don't set this

config.active_record.whitelist_attributes = false

until you've fully migrated over.

Upvotes: 1

Related Questions