基于StackOverlfow上的先前问答,我在application.rb中添加了以下内容:
config.active_record.whitelist_attributes = false
因为我收到的类型错误无法大量分配受保护的属性
在我这样做之后,好像一切都运转良好。我现在得到同样的错误,但这是一个假阴性。请注意,即使我收到错误,该列实际上也会更新。
这是调试器输出:
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行重定向用户吗?为什么我在更新发生时也会收到错误?
答案 0 :(得分:1)
您应该将whitelist_attributes设置为true,并出于安全原因在每个模型中使用attr_accessible。以下是有关的信息:
http://guides.rubyonrails.org/security.html#mass-assignment
另外,请阅读Niiru的上述内容。
编辑:
在你的控制流程中,我认为它没有做你想要的。如果它到达第74行,它可能会通过第一个if条件
if params[:category][:update_admins_field]
然后第二次失败,如果
if @category.update_attribute(:admins,params['admins'])
然后退出if if / else / end并继续到第74行,因为还没有回复。要解决这个问题,我想你想要这样的事情:
if admin category
if update admin
return success
else
return failure
end
else
if update normal
return success
else
return failure
end
end