Search code examples
ruby-on-railsmass-assignmentattr-accessibleattr-protected

Assignment of a protected attribute in Rails


I have a field on my User model that is protected because it determines clearance level. So it should be left protected and not mass-assignable. So even though attributes are protected by default in 3.2, that is actually the behavior I want.

However, on one controller method, I want to allow a manager to assign this field, for instance on user creation or user update.

How do I allow the assignment of that attribute for specific controller actions?

For example, I have my controller:

# app/controllers/admin/users_controller.rb

def create
    @user = User.new(params[:user])
# ...
end

Now what I would do is exclude clearance from params[:user], but it seems to get filtered out and raise and exception even before that line is reached (I tried putting a debugger right before that line and even comment it out, it still raised an exception).

Where do protected attributes get caught, if not when calling User#new?


Solution

  • The Rails way to do this would be to assign the attributes without protection or to use an admin role:

    @user = User.new
    @user.assign_attributes(params[:user], :without_protection => true)
    @user.save
    

    However, I found this to be a little tedious so I wrote a gem called sudo_attributes that gives (in my opinion) a better API:

    @user = User.sudo_new(params[:user])
    @user.save
    

    It mimics all of the Rails instantiation, creation, and updating methods (new, build, create, create!, update_attributes, etc).