简体   繁体   中英

Rails 4.2: Getting “Unpermitted parameters” on user creation after adding `protected_attributes` gem

I am upgrading from Rails 3.2 to 4.2 and wanted to follow Ryan Bates' advice of getting things working as quickly as possible before doing any major refactoring.

To that end, I installed the protected_attributes gem because I was under the impression that with this gem installed I wouldn't need to implement the strong params approach in my controllers immediately and could continue using attr_accessible in the models until I have time to refactor.

I'm not getting any errors about attr_accessible itself, but when I try to create a user in development I get Unpermitted parameters: first_name, last_name, phone despite having all of those as arguments in the User model's attr_accessible method.

Can someone point out what I'm doing wrong here?

That's not the correct approach. Instead of porting a legacy, deprecated feature from 3.2 to 4.2, what you really want to do instead is the opposite: install strong_parameters gem in Rails 3.2 and make sure to replace the attr_accessible before the upgrade.

Rails 4.x is not really designed to use protected attributes anymore, therefore you will encounter a lot of issues trying to reintroduce it.

To use strong params you will have to update your controller's code (which is what I recommend to do, since it won't cost too much work).

In general the implementation of using strong_parameters is as follows:

  def create
    @model = Model.create(model_params)
    if @model.persisted?
      # logic
    else
      #logic
    end
  end

private

def model_params
  params.require(:model).permit(:model_attrbite1, :model_attribute2)
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM