这是我的两个模型:
class Article < ActiveRecord::Base
attr_accessible :content
has_many :comments
end
class Comment < ActiveRecord::Base
attr_accessible :content
belongs_to :article
end
我正在尝试使用以下代码在 seed.rb 中播种数据库:
Article.create(
[{
content: "Hi! This is my first article!",
comments: [{content: "It sucks"}, {content: "Best article ever!"}]
}],
without_protection: true)
但是,耙子db:seed给了我以下错误消息:
rake aborted!
Comment(#28467560) expected, got Hash(#13868840)
Tasks: TOP => db:seed
(See full trace by running task with --trace)
可以像这样为数据库播种吗?
如果是后续问题:我已经搜索了一些,似乎要进行这种(嵌套的?)质量分配,我需要为我要分配的属性添加"accepts_nested_attributes_for"。(可能类似于注释模型的"accepts_nested_attributes_for :article")
有没有办法允许这类似于"without_protection:真实"?因为我只想在播种数据库时接受这种批量分配。
您看到此错误的原因是,当您将关联的模型分配给另一个模型时(如 @article.comment = 注释),右侧应该是实际对象,而不是对象属性的哈希。
如果要通过传入注释的参数来创建文章,则需要包含 accepts_nested_attributes_for :comments
项目模型中,并将:comments_attributes
添加到attr_accesible
列表中。
这应该允许你上面写的内容。
我不认为有可能有条件的质量分配,因为这可能会损害安全性(从设计的角度来看)。
编辑:您还需要更改评论:[{content: "It sucks"}, {content: "Best article ever!"}]
到comments_attributes: [{content: "It sucks"}, {content: "Best article ever!"}]