Skip to content

Instantly share code, notes, and snippets.

@rajivm
Created April 22, 2015 18:49
Show Gist options
  • Save rajivm/b4d318c73f574e559080 to your computer and use it in GitHub Desktop.
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)
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
@rajivm
Copy link
Author

rajivm commented Apr 22, 2015

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 of include 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment