【问题标题】:Seed has_many relation using mass assignment使用质量分配的种子 has_many 关系
【发布时间】:2012-06-13 22:12:51
【问题描述】:

这是我的两个模型:

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'?因为我只想在做种数据库的时候接受这种海量赋值。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 activerecord mass-assignment


    【解决方案1】:

    您看到此错误的原因是当您将关联模型分配给另一个模型时(如@article.comment = comment),预计右侧是实际对象,而不是对象属性。

    如果你想通过为评论传入参数来创建文章,你需要包含 在文章模型中添加accepts_nested_attributes_for :comments 并将:comments_attributes 添加到attr_accesible 列表中。

    这应该允许您在上面写的内容。

    我认为不可能进行有条件的批量分配,因为这可能会损害安全性(从设计的角度来看)。

    编辑:您还需要将 cmets:[{content: "It sucks"}, {content: "Best article ever!"}] 更改为 comments_attributes: [{content: "It sucks"}, {content: "Best article ever!"}]

    【讨论】:

    • 谢谢,它有效。现在唯一的问题是不再需要“without_protection: true”。我真的不喜欢公开更多的模型,只是为了更方便地为数据库播种:/
    • 您在这里公开的唯一新属性是 :comment_attributes,并且由于这些只是转发到 Comment 模型(其中唯一可访问的属性是 :content),您实际上并没有再公开的模型比以前。
    • 换句话说, :cmets_attributes 并不是模型的真正组成部分,而是模型属性的散列(无论如何都可以访问)。
    • @cdesrosiers 我怎样才能给你买啤酒来回答这个问题??我一直在这几个小时。谢谢!!!
    猜你喜欢
    • 1970-01-01
    • 2015-01-05
    • 2012-06-23
    • 2013-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多