【问题标题】:Not sure why my rake seed file isn't running不知道为什么我的 rake 种子文件没有运行
【发布时间】:2020-08-21 20:35:57
【问题描述】:

这是我的种子文件:

require 'pry'
require 'rest-client'
require 'json'
require 'faker'

Consumer.delete_all
AlcoholicBeverage.delete_all
Intake.delete_all

100.times do 
    name = Faker::Name.first_name
    sex= Faker::Gender.binary_type
    weight= Faker::Number.between(from: 1, to: 10)
    Consumer.create!(name:name,sex:sex,weight:weight)
end

ingredients=RestClient.get("https://raw.githubusercontent.com/teijo/iba-cocktails/master/recipes.json")
@ingredients_data=JSON.parse(ingredients)

@ingredients_data.collect do |x,y|
    AlcoholicBeverage.create(cocktail_name: x["name"],glass: x["glass"],garnish: x["garnish"],preparation: x["preparation"])
end

100.times do 
    consumer_id = rand(1..100)
    alcoholic_beverage_id = rand(1..100)
    Intake.create!(consumer_id: consumer_id, alcoholic_beverage_id:alcoholic_beverage_id)
end

这是我的 gemfile:

# frozen_string_literal: true
source "https://rubygems.org"

gem "activerecord", '~> 5.2'
gem "sinatra-activerecord"
gem "sqlite3", '~> 1.3.6'
gem "pry"
gem "require_all"
gem "faker"
gem 'rest-client'

我已经很好地运行了我的迁移.. 所以我不确定为什么当我在终端中输入 rake db:seed 时什么都没有显示。 任何建议或帮助将不胜感激。我也尝试在我的种子文件中包含 require 'faker' ,但它并没有改变任何事情。

【问题讨论】:

  • 什么都没有显示?甚至没有错误消息?该命令只是返回空而没有任何反馈?
  • 小心:调用delete_all 不会重置您的自动增量列,并且不会与您的rand 设置关联
  • 使用rails c 打开一个rails 控制台,然后将所有内容粘贴到文件中——您是否收到错误消息?你看到正在创建的记录吗?必须有一些成功或失败的迹象。
  • 也许你有两个seeds.rb 文件?您将上述seeds.rb 文件保存在哪里?它应该在这里db/seeds.rb。注意文件名是复数:seeds.rb
  • @JoshBrody 如何重置我的自动增量列?

标签: ruby rake database-migration faker


【解决方案1】:

这种替代方法将帮助您避免丢失数据,而不依赖于您的 id 从 1 到 100:

consumers = 100.times.map do 
  name = Faker::Name.first_name
  sex= Faker::Gender.binary_type
  weight= Faker::Number.between(from: 1, to: 10)
  Consumer.create!(name:name,sex:sex,weight:weight)
end

ingredients=RestClient.get("https://raw.githubusercontent.com/teijo/iba-cocktails/master/recipes.json")
@ingredients_data=JSON.parse(ingredients)

beverages = @ingredients_data.map do |x,y|
  AlcoholicBeverage.create(cocktail_name: x["name"],glass: x["glass"],garnish: x["garnish"],preparation: x["preparation"])
end

100.times do 
  Intake.create!(consumer: consumers.shuffle.first, alcoholic_beverage: beverages.shuffle.first)
end

【讨论】:

    猜你喜欢
    • 2022-08-21
    • 2015-04-23
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-08
    相关资源
    最近更新 更多