【问题标题】:seeding with has_one, has_many and through associations使用 has_one、has_many 和通过关联进行播种
【发布时间】:2016-03-15 21:19:28
【问题描述】:

我正在运行 rake db:seed 命令,它没有给出任何错误。但是,我没有通过控制台Event.find(1) 或服务器localhost:3000/events/ 找到此事件。我知道我肯定在某个地方搞砸了。 协会:

class Event < ApplicationRecord
  has_one :lineup
  has_many :artists, :through => :lineup
  belongs_to :venue
end

种子.rb:

Event.create(name: "The function", 
             date: DateTime.new(2016,2,3,10,0,0,'+7'), 
             venue: Venue.create(name: "Speakeasy", address: "Lynwood Ave", zip_code: "30312"), 
             lineup: Lineup.create(:artist => Artist.create(name: "DJ Sliink", bio: "jersey club king")), 
             description: "free free free")

【问题讨论】:

    标签: ruby-on-rails associations seeding


    【解决方案1】:

    .create 中的任何一个方法都可能静默验证失败。

    来自the create docs

    无论对象是否成功保存到数据库,都会返回结果对象。

    尝试改用create!;如果无法保存记录,则会引发异常。

    我建议在 seeds.rb 的任何地方使用 create! 以避免静默失败。

    【讨论】:

    • 是的,这有帮助!事实证明,我对其建模的方式是,如果没有 Event,就无法创建 Lineup
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多