ruby-on-rails - 使用质量分配的种子 has_many 关系

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

这是我的两个模型:

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_attributesattr_accesible 列表。

这应该考虑到您上面所写的内容。

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

编辑:您还需要更改评论:[{content: "It sucks"}, {content: "Best article ever!"}]comments_attributes: [{content: “糟透了”},{内容:“有史以来最好的文章!”}]

关于ruby-on-rails - 使用质量分配的种子 has_many 关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10972777/

相关文章:

ruby-on-rails - 将 rails 4.1 升级到 4.2 列名称问题

mysql - 高效查询多语言类别和类别项

ruby-on-rails - 将 "Like/Unlike"按钮添加到 Rails 中的帖子

ruby-on-rails - Rails - 在模型中动态定义实例方法

ruby - 使用 ruby​​ 类中的方法进行迭代

mysql - rails 服务器命令无法找到库

ruby-on-rails - 如何在 OSX 上安装 Ruby on Rails 3?

ruby-on-rails-3 - collection_select 方法在 Rails 3.1.1 中给出错误

ruby-on-rails - has_many 条件或 proc 外键

ruby-on-rails - 在 Rails 环境之外测试(使用 RSpec) Controller