【问题标题】:Fails to create upon seeding播种时创建失败
【发布时间】:2016-04-03 04:56:15
【问题描述】:

Articlehas_oneTitle。在播种新标题时,我收到错误(参考下面我的种子代码的第 4 行):

NoMethodError: undefined method `create!' for nil:NilClass

是什么导致了这个错误?好像说diagram是nil,但怎么可能呢?

种子:

articles = Article.all
articles.each do |article|
  content = Faker::Lorem.paragraphs(2)
  article.title.create!( content: content )
end

文章型号:

has_one :title, dependent: :destroy

标题模型:

belongs_to :article

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 associations seed


    【解决方案1】:

    错误消息显示article.title 为 nil,鉴于这是您要创建的内容,这是正确的。

    您应该使用关联为您提供的方法 - 在这种情况下您想要:

    article.create_title!(content: content)
    

    参考:http://guides.rubyonrails.org/association_basics.html#has-one-association-reference

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-10
      • 2021-08-13
      • 1970-01-01
      • 1970-01-01
      • 2022-12-03
      • 2018-12-22
      • 1970-01-01
      相关资源
      最近更新 更多