使用 has_one、has_many 和通过关联进行播种

seeding with has_one, has_many and through associations

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

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

seed.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")

有可能 .create 方法中的任何一个都没有通过验证。

来自the create docs

The resulting object is returned whether the object was saved successfully to the database or not.

请尝试使用 create!;如果无法保存记录,它将引发异常。

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