这是我的两个模型:
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)
但是 rake 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”。 (对于 Comment 模型,可能类似于 'accepts_nested_attributes_for :article')
有没有办法让这个类似于'without_protection: true'?因为我只想在做种数据库的时候接受这种批量赋值。
最佳答案
您看到此错误的原因是,当您将关联模型分配给另一个模型时(如@article.comment = comment),预计右侧是实际对象,而不是对象属性。
如果你想通过为评论传递参数来创建文章,你需要包括
accepts_nested_attributes_for :comments
在文章模型中添加 :comments_attributes
到 attr_accesible
列表。
这应该考虑到您上面所写的内容。
我不认为有条件的批量分配是可能的,因为这可能会损害安全性(从设计的角度来看)。
编辑:您还需要更改评论:[{content: "It sucks"}, {content: "Best article ever!"}]
到 comments_attributes: [{content: “糟透了”},{内容:“有史以来最好的文章!”}]
关于ruby-on-rails - 使用质量分配的种子 has_many 关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10972777/