0

基于之前关于 StackOverlfow 的问答,我在 application.rb 中添加了以下内容:

 config.active_record.whitelist_attributes = false

因为我遇到了 Can't mass-assign protected attributes 类型的错误

在我这样做之后,似乎一切正常。我现在遇到了同样的错误,但这是一个假阴性。请注意,即使我收到错误,该列实际上也已更新。

这是调试器输出:

Started PUT "/categories/5" for 127.0.0.1 at 2012-07-09 11:26:40 -0700
Processing by CategoriesController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"SifcfX29c+mGRIJXvUWGnZ8mBelMm4uZloYsoO317SY=", "admin_selections"=>{"admin1"=>"56", "admin2"=>"55", "admin3"=>"", "admin4"=>"", "admin5"=>"", "admin6"=>"", "admin7"=>"", "admin8"=>""}, "category"=>{"update_admins_field"=>"1"}, "commit"=>"Update Category", "id"=>"5"}
  Category Load (0.2ms)  SELECT `categories`.* FROM `categories` WHERE `categories`.`id` = 5 LIMIT 1
   (0.1ms)  BEGIN
   (0.2ms)  UPDATE `categories` SET `admins` = '[\"56\",\"55\",\"\"]', `updated_at` = '2012-07-09 18:26:40' WHERE `categories`.`id` = 5
   (1.3ms)  COMMIT
   (0.1ms)  BEGIN
   (0.1ms)  ROLLBACK
Completed 500 Internal Server Error in 5ms

ActiveModel::MassAssignmentSecurity::Error (Can't mass-assign protected attributes: utf8, _method, authenticity_token, category, commit, action, controller, id):
  app/controllers/categories_controller.rb:74:in `block in update'
  app/controllers/categories_controller.rb:62:in `update'

似乎 MySQL 代码已正确生成,但随后出现回滚和 500 错误。

以下是 categories_controller.rb 中的相关代码:

def update
  @category = Category.find(params[:id])
  respond_to do |format| #this is line 62
    if params[:category][:update_admins_field]
      params['admins'] = return_admins_json (params)
      if @category.update_attribute(:admins,params['admins'])
        format.html { redirect_to @category, notice: 'Category was successfully updated.' } #line 66
        format.json { head :no_content }
      end
    else
      format.html { redirect_to @category, notice: 'Category was not successfully updated.' }
      format.json { head :no_content }
    end

    if @category.update_attributes(params)  #line 74
      format.html { redirect_to @category, notice: 'Category was successfully updated.' }
      format.json { head :no_content }
    else
      format.html { render action: "edit" }
      format.json { render json: @category.errors, status: :unprocessable_entity }
    end
  end
end  

为什么会到第 74 行?用户不应该在第 66 行被重定向吗?为什么更新时我也会收到错误消息?

4

1 回答 1

1

您应该将 whitelist_attributes 设置为 true,并出于安全原因在每个模型中使用 attr_accessible。以下是相关信息:

http://guides.rubyonrails.org/security.html#mass-assignment

另外,请阅读上面 Niiru 的评论。

编辑:

在您的控制流程中,我认为它没有按照您的意愿行事。如果它到达第 74 行,它可能通过了第一个 if 条件

if params[:category][:update_admins_field]

然后失败了第二个 if

if @category.update_attribute(:admins,params['admins'])

然后退出 if/else/end 并继续执行第 74 行,因为尚未调用 return。为了解决这个问题,我认为你想要这样的东西:

if admin category
   if update admin
      return success
   else
      return failure
   end
else
   if update normal
      return success
   else
      return failure
   end
end
于 2012-07-09T19:15:14.650 回答