首页 > 解决方案 > Rails 6.0 Seed.rb 文件在运行 rails db:seed 后未保存到 sqlite3 db

问题描述

Rails 6.0(初级)我的种子文件在运行后没有保存到我的数据库中rails db:seed --trace

我得到以下输出:

** Invoke db:seed (first_time)
** Invoke db:load_config (first_time)
** Invoke environment (first_time)
** Execute environment
** Execute db:load_config
** Execute db:seed
** Invoke db:abort_if_pending_migrations (first_time)
** Invoke db:load_config 
** Execute db:abort_if_pending_migrations

正如它所说,如果等待迁移,则中止。我运行 rails db:migrate 只是为了安全起见,但它们都是最新的,所以什么也没做。

load_config我需要做些什么吗?

注意:我通过这个过程在这个表中创建了 2 个条目,同时试图让它工作。表中的先前条目会阻止种子工作吗?

下面的种子文件

def time_rand from = 0.0, to = Time.now
    Time.at(from + rand * (to.to_f - from.to_f))
end

  event_list = [
    ["My headline", 
    "this is a very long description of text", 
    "Physical Location", 
    "Locations url", 
    time_rand, 
    "this is a shorter description of words", 
    "https://www.ticketmaster.com/", 
    "google maps url",
    "123 Fake Street", 
    "Brooklyn", 
    "11123", 
    "NY", 
    "USA" ]
]

event_list.each do |headline, d_long, location_name, location_url, image_url, time, d_short, tickets_url, map_url, location_street, location_city, location_zip, location_state, location_country|
    temp = Event.create(
                headline: headline, 
                description_long: d_long, 
                location_name: location_name, 
                location_url: location_url, 
                time: time, 
                description_short: d_short, 
                tickets_url: tickets_url, 
                map_url: map_url, 
                location_street: location_street,
                location_city: location_city,
                location_zip: location_zip,
                location_state: location_state,
                location_country: location_country
    )
    temp.save
end

编辑:感谢 Sebastian 提出模型验证。虽然我认为我仍在完成验证,但这里的模型文件是:

class Event < ApplicationRecord
    validates :headline, presence: true, length: { minimum: 3 }
    validates :description_short, presence: true, length: { minimum: 3 }
    validates :location_name, presence: true
    validates :time, presence: true
end

标签: ruby-on-railsrubyruby-on-rails-6seed

解决方案


感谢 Sebastian Palma 的使用 byebug的建议,我想通了:-我有一个未命中的参数计数,所以给了时间一个字符串。- temp.time 也给了我一个零,因此被验证拒绝。我最终只是硬编码了一些时间值,以确保它最终通过。

经验教训:计算你的参数并使用 byebug


推荐阅读