新手问题 Rails 4 Can't mass-assign protected attributes for XXXcontroller

yutian · 2013年07月25日 · 最后由 reyesyang 回复于 2013年07月26日 · 3870 次阅读

使用 rails4 从前台获取参数,在 create 的时候出错,提示信息如下:

WARNING: Can't mass-assign protected attributes for  XXX: name, spell_code, , insurance_number
    app/controllers/XXXX_controller.rb:32:in `create'
   (0.2ms)  BEGIN
  SQL (5.7ms)  INSERT INTO "XXXX" ("created_at", "updated_at") VALUES ($1, $2) RETURNING "id"  [["created_at", Thu, 25 Jul 2013 14:20:45 UTC +00:00], ["updated_at", Thu, 25 Jul 2013 14:20:45 UTC +00:00]]

保存到数据库时候,参数消失,只保存了 create update _at 两个信息, 折腾了一天了,崩溃 ing,求教各位大侠赐教@lgn21st @Rei

#1 楼 @Rei 嗯,你的方案是正解。

#1 楼谢谢 @Rei 最终在 model 中添加了一行 attr_accessible :name :email 问题是解决了。 rails4 的 model 现在是空的,在 controller 里面有了个 def patient_params params.require(:patient).permit(:name :email) end 另外一个项目(rails4)里面 model 没有添加 attr_accessible 数据也能添加成功,但是同样是 rails4 的这个项目就必须要添加 attr_accessible,还是不明白到底怎么回事。

#2 楼 @lgn21st 现在问题解决 看了http://weblog.rubyonrails.org/2012/3/21/strong-parameters/ 里面提到 We should never have put mass-assignment protection into the model, 这个和我在 model 里面写 attr_accessible 是不是矛盾啊

#5 楼 @yutian 有设置可以关掉属性白名单,新创建 rails 4 项目是不带白名单的。

#5 楼 @yutian attr_accessible 是 Rails4 之前使用的避免 mass-assignment 攻击的手段,相应的保护逻辑是在 Model 中声明的。从 Rails4 开始推荐使用 strong parameters,也就是将相应的声明移到了 Controller 中,这样控制粒度可以更细,而且比较直观。strong parameters 和 attr_accessible 是同一目的不同的新老技术实现,是相互替代的关系。所以就在介绍 strong parameters 的文章中说“We should never have put mass-assignment protection into the model”也就不矛盾了。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号