ActiveModel::ForbiddenAttributesError using update_attributes having created params hash myself

﹥>﹥吖頭↗ 提交于 2019-12-04 06:59:35

In DevicesController#update action, change

@device.update_attributes(params[:device])

To

@device.update_attributes(device_params)

As you are using Rails 4.1, you need to whitelist the attributes which you would like to be inserted/updated in database. As you passed the attributes directly to update_attributes method without permitting them you received ActiveModel::ForbiddenAttributesError

UPDATE

To resolve param not found: device:

  def device_params
    if params[:device]
      params.require(:device).permit(:device, :name, :email, :password, :password_confirmation, :encrypted_password, :salt, :role_ids, :is_admin, :chg_pwd)  # TODO minimize when update is working 
    end
  end

The fix was to add the fields as attr_accessor to the model, but not the database, so that it could be used correctly within the form.

  attr_accessor :is_admin, :chg_pwd

And then modify the view to:

<%= simple_form_for @device do |f| %>
    <legend><%= controller.action_name.capitalize %> Device:</legend>
    <%= f.input :name, disabled: true %>
    <%= f.input :is_admin, as: :boolean, checked_value: true, unchecked_value: false %>
    <%= f.input :chg_pwd, as: :boolean, checked_value: true, unchecked_value: false %>
    <%= f.button :submit %>
<% end %>

Then, due to the Application Controller code from Anton Trapp:

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

I was able to update the fields in Device Controller as follows:

@device.update_attributes(params[:device])
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!