简体   繁体   English

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

[英]seeding with has_one, has_many and through associations

I'm running the rake db:seed command and it doesn't give any errors.我正在运行 rake db:seed 命令,它没有给出任何错误。 However, I'm not finding this Event through the console Event.find(1) or through the server localhost:3000/events/ .但是,我没有通过控制台Event.find(1)或服务器localhost:3000/events/找到此事件。 I know I'm definitely messing up somewhere.我知道我肯定在某个地方搞砸了。 the associations:协会:

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

seed.rb:种子.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")

It's possible that any of the .create methods are silently failing validations.任何.create方法都可能会默默地失败验证。

From the create docs :create文档

The resulting object is returned whether the object was saved successfully to the database or not.无论对象是否成功保存到数据库,都会返回结果对象。

Try using create!尝试使用create! instead;反而; it will raise an exception if the record could not be saved.如果无法保存记录,它将引发异常。

I would recommend using using create!我建议使用使用create! everywhere in seeds.rb to avoid silent failures.seeds.rb随处可见,以避免无声失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM