Rails 错误:无法批量分配受保护的属性 [英] Rails error: Can't mass-assign protected attributes

查看:33
本文介绍了Rails 错误:无法批量分配受保护的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个非常简单的 AddressBook rails 应用程序.但是,我收到此错误无法批量分配受保护的属性:city_id".我怎样才能解决这个问题?请随时在您对以下 Rails 代码的回答中添加任何评论/建议.谢谢.

I am trying to build an extremely simple AddressBook rails application. However, I am getting this error "Can't mass-assign protected attributes: city_id". How can I fix this? Please feel free to add any comment/suggestion to your answer regarding the rails code below. Thanks.

我是如何创建项目的(从头开始):

How I created the project (from scratch):

rails new demo
rails generate model City name:string
rails generate scaffold User name:string city:references
rake db:migrate

db/seeds.db:

db/seeds.db:

City.create(name: "City1")
City.create(name: "City2")
City.create(name: "City3")

耙分贝:种子

将这一行 <%= f.text_field :city %>app/views/users/_form.html.erb 更改为 <%= f.collection_select :city_id, City.all, :id, :name %>

changed this line <%= f.text_field :city %> from app/views/users/_form.html.erb to <%= f.collection_select :city_id, City.all, :id, :name %>

user.rb 自动生成的行 belongs_to :city 更改为 has_one :city.

changed user.rb auto-generated line belongs_to :city to has_one :city.

belongs_to :city 添加到 city.rb

P.S:我使用的是 Rails 3.2.3 和 Ruby 1.9.3.

P.S: I am using Rails 3.2.3 and Ruby 1.9.3.

推荐答案

rails 3.2.3 有一个重要的安全更改,要求您通过将 config.active_record.whitelist_attributes 设置为显式允许批量分配

There was an important security change rails 3.2.3 that requires you to allow mass assignment explicitly by setting config.active_record.whitelist_attributes to false

https://weblog.rubyonrails.org/2012/3/30/ann-rails-3-2-3-has-been-released/

http://www.h-online.com/security/news/item/Rails-3-2-3-makes-mass-assignment-change-1498547.html

或者(更好),您只需为模型中您希望能够更改的属性设置attr_accessible,而不是允许批量分配,例如

alternatively (and better), instead of allowing mass assignment, you just have to set the attr_accessible for the attributes in your model that you want to be able to change, e.g.

attr_accessible :city_id, :name # list all fields that you want to be accessible here

请查看 rails 安全指南以了解有关 rails 中批量赋值的更多信息.

Please check the rails security guide for more information about mass-assignment in rails.

这篇关于Rails 错误:无法批量分配受保护的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆