1

这是我的两个模型:

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'?因为我只想在播种数据库时接受这种批量分配。

4

1 回答 1

4

The reason you are seeing this error is that when you assign an associated model to another model (as in @article.comment = comment), it is expected that the right hand side be an actual object, not a hash of the object attributes.

If you want to create an article by passing in parameters for a comment, you need to include accepts_nested_attributes_for :comments in the article model and add :comments_attributes to the attr_accesible list.

This should allow for what you've written above.

I don't believe it is possible to have conditional mass-assignment as this might compromise security (from a design standpoint).

EDIT: You also need to change comments: [{content: "It sucks"}, {content: "Best article ever!"}] to comments_attributes: [{content: "It sucks"}, {content: "Best article ever!"}]

于 2012-06-10T22:32:23.893 回答