问题描述
我正在阅读下面的这篇文章.http://tutorials.jumpstartlab.com/projects/blogger.html#i2:-adding-comments
I was going through this article below. http://tutorials.jumpstartlab.com/projects/blogger.html#i2:-adding-comments
下面是我们创建一个新的Comment
对象并将associate
与相应的article
的代码.
Below is the code where we create a new Comment
object and associate
with corresponding article
.
@comment = Comment.new
@comment.article_id = @article.id
谁能解释一下作者在下面想说什么.任何人都可以告诉我如何在没有安全问题的情况下做其他事情以便更好地理解.
Can anyone explain me what the author is trying to say below. Can anyone show me how to do otherwise without the security thing for better understanding.
由于 Rails 的批量赋值保护,article_id
新的Comment
对象的属性需要手动赋值带有文章
的id
.
推荐答案
您正在阅读的文章指的是 rails 3.Rails 3 不像 Rails 4 那样使用强参数,而是使用 attr_accessible
带有允许批量分配的属性列表.
The article you were reading was referring to rails 3. Rails 3 doesn't use strong parameters like Rails 4 and instead uses attr_accessible
with a list of attributes which are permitted to be mass assigned.
在 ruby 中,批量赋值就是在 new
、create
或 assign_attributes
等方法中使用散列一次设置多个变量的一切.通常情况下,允许批量分配外键并不是一个好主意.
Mass assignment in ruby is everything where you use a hash to set multiple variables at once in methods like new
, create
or assign_attributes
. Quite often it is not a good idea to allow mass assignment of foreign keys.
总而言之,作者的意思是这两行不能写成:
In summary, author meant that those two lines cannot be written as:
@comment = Comment.new(article_id: @article.id)
由于 article_id
未在 attr_accessible
中列出,因此会引发批量分配安全异常.
since article_id
is not listed in attr_accessible
and it will raise Mass Assignment security exception.
这篇关于轨道中的批量分配问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!