Forbidden Attributes Error in Rails 4 when encountering a situation where one would have used attr_accessible in earlier versions of Rails

Ecnalyr picture Ecnalyr · Jul 3, 2013 · Viewed 67.5k times · Source

With the recent upgrade to Rails 4, updating attributes using code resembling the below does not work, I get a ActiveModel::ForbiddenAttributes error:

@user.update_attributes(params[:user], :as => :admin)

Where User has the following attr_accessible line in the model:

attr_accessible :role_ids, :as =>admin
# or any attribute other than :role_ids contained within :user

How do you accomplish the same task in Rails 4?

Answer

Ecnalyr picture Ecnalyr · Jul 3, 2013

Rails 4 now has features from the strong_parameters gem built in by default.

One no longer has to make calls :as => :admin, nor do you need the attr_accessible :user_attribute, :as => admin in your model. The reason for this is that, by default, rails apps now have 'security' for every attribute on models. You have to permit the attribute you want to access / modify.

All you need to do now is call permit during update_attributes:

@user.update_attributes(params[:user], permit[:user_attribute])

or, to be more precise:

@user.update_attributes(params[:user].permit(:role_ids))

This single line, however, allows any user to modify the permitted role. You have to remember to only allow access to this action by an administrator or any other desired role through another filter such as the following:

authorize! :update, @user, :message => 'Not authorized as an administrator.'

. . . which would work if you're using Devise and CanCan for authentication and authorization.