Created
April 22, 2015 18:49
-
-
Save rajivm/b4d318c73f574e559080 to your computer and use it in GitHub Desktop.
Rails 3 Forbidden Attributes with soft failures (i.e. in production, allow params anyways, but log the problem)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module ActiveModel | |
class ForbiddenAttributes < StandardError | |
end | |
module SoftForbiddenAttributesProtection | |
def sanitize_for_mass_assignment(*options) | |
new_attributes = options.first | |
if !new_attributes.respond_to?(:permitted?) || new_attributes.permitted? | |
super | |
elsif Rails.env.production? | |
logger.error("ActiveModel::ForbiddenAttributes") | |
super | |
else | |
raise ActiveModel::ForbiddenAttributes | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
When introducing Strong Parameters / ForbiddenAttributes for the first time into a Rails 3 codebase, in prep for migration to Rails 4, this allows you to deploy to production without fear of everything breaking.
include ActiveModel::SoftForbiddenAttributesProtection
instead ofinclude ActiveModel::ForbiddenAttributesProtection
. This is designed to still fail hard in development and staging environments so that you can catch problems. This is different than the rails built-in logging mode because this still causes the attributes to be filtered, whereas this will allow them to pass through.In production: logging
In development/staging: raise Exception