基于之前关于 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 行被重定向吗?为什么更新时我也会收到错误消息?