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

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.


If you create a new Rails 4 site you'll notice that generated controllers now include a private method which you use to receive your sanitised params. This is a nice idiom, and looks something like this:

private

  def user_params
    params.require(:user).permit(:username, :email, :password)
  end

The old way of allowing mass assignment was to use something like:

attr_accessible :username, :email, :password

on your model to mark certain parameters as accessible.

Upgrading

To upgrade you have several options. Your best solution would be to refactor your controllers with a params method. This might be more work than you have time for right now though.

Protected_attributes gem

The alternative would be to use the protected_attributes gem which reinstates the attr_accessible method. This makes for a slightly smoother upgrade path with one major caveat.

Major Caveat

In Rails 3 any model without an attr_accessible call allowed all attributes though.

In Rails 4 with the protected_attributes gem this behaviour is reversed. Any model without an attr_accessible call has all attributes restricted. You must now declare attr_accessible on all your models. This means, if you haven't been using attr_accessible, you'll need to add this to all your models, which may be as much work as just creating a params method.

https://github.com/rails/protected_attributes


This problem might also be caused by the Cancan gem

Just add to application_controller.rb

before_filter do
  resource = controller_name.singularize.to_sym
  method = "#{resource}_params"
  params[resource] &&= send(method) if respond_to?(method, true)
end

Works without any further modifications of code got it from here: https://github.com/ryanb/cancan/issues/835#issuecomment-18663815