Created
March 7, 2012 02:55
-
-
Save mgreenly/1990590 to your computer and use it in GitHub Desktop.
mass assignment params slice
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
| # a variation on DHH's slice pattern for the mass assignment problem that may save on typing | |
| # in common situations. Since it seems to me that most of the time there are only a small | |
| # number of attributes that have authorization limited by role it would be nice if they were | |
| # the only one's you had to specify. | |
| # none of this was tested it may not actually work! | |
| # since this is the same for every class just put it in a common base class | |
| class ActiveRecord::Base | |
| def self.white_list | |
| defined?(accessible_attributes) ? accessible_attributes.map(&:to_sym) : [] | |
| end | |
| end | |
| # you're forced to define attr_accessible if you use the slice pattern in your controllers | |
| # because white_list will return an emtpy array if you don't | |
| class Post < ActiveRecord::Base | |
| attr_accesible :title, :content, :published | |
| end | |
| # this is pretty much what DHH wrote except I like the name safe_params better than post_params | |
| class PostsController < ActionController::Base | |
| def create | |
| Post.create(safe_params) | |
| end | |
| def update | |
| Post.find(params[:id]).update_attributes!(safe_params) | |
| end | |
| def safe_params | |
| if current_user.admin? | |
| params[:post].slice(Post.white_list) | |
| else | |
| # it's easy to remove the one attribute you don't want for none admins | |
| # which may not seem like a big deal in this example but would be if | |
| # the model had 20 accessible attributes and only 1 varried | |
| params[:post].slice(Post.white_list - [:published]) | |
| # it would also have been easy to define a group of attributes in as a constant | |
| # array and use it instead | |
| RESTRICTED_ATTRIBUTES = [:published] | |
| params[:post].slice(Post.white_list - RESTRICTED_ATTRIBUTES) | |
| end | |
| end | |
| end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment