Skip to content

Instantly share code, notes, and snippets.

@cpjolicoeur
Created March 6, 2012 14:20
Show Gist options
  • Select an option

  • Save cpjolicoeur/1986526 to your computer and use it in GitHub Desktop.

Select an option

Save cpjolicoeur/1986526 to your computer and use it in GitHub Desktop.
Rails Mass Assignment Solutions

Initializer

# config/initializers/mass_assignment.rb
ActiveRecord::Base.send(:attr_accessible, nil)

Whitelist Config

From rails core commit 641a4f6240

# config/application.rb
config.active_record.whitelist_attributes = true

Params slice

class FooController << ActionController::Base
  def create
    @foo = Foo.new(post_params)
    ...
  end

  def update
    @foo.update_attributes(post_params)
    ...
  end

  def post_params
    @params[:foo].slice(:params, :i_care_about)
  end
  private :post_params
end
@bsimpson

bsimpson commented Mar 6, 2012

Copy link
Copy Markdown

You may want to look at the new(ish) ActiveModel::MassAssignmentSecurity module. It looks like you can filter the attributes in either the controller, or the model via attr_accessible with an ":as" option. This allows for different lists of accessible attributes based on a role. An admin would be able to update more attributes than a normal user, etc. The params can be filtered using sanitize_for_mass_assignment which looks like it may duplicate what you are doing in the post_params method in your controller.

http://api.rubyonrails.org/classes/ActiveModel/MassAssignmentSecurity/ClassMethods.html

@cpjolicoeur

cpjolicoeur commented Mar 6, 2012 via email

Copy link
Copy Markdown
Author

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