带有外键的种子数据库 - seeds.rb

Seed database with foreign key - seeds.rb

我正在尝试使用 Faker gem 为数据库播种,当我尝试只为电影播种时,我成功了,但是当我尝试为每部电影播种时,每部电影都有 1-10 条评论,我得到了一堆不同的错误取决于我改变了什么。

这是我的 seeds.rb 的样子:

require 'faker'

formats = %w[Beta VHS IMAX HD SuperHD 4K DVD BluRay]
genres = %w[Triller Comedy Horror Action Drama SciFi Documentary]
images = %w[magento.svg mysql.svg php.svg jquery.svg mongodb.svg prestashop.svg meteor.svg]

Movie.destroy_all
Comment.destroy_all

100.times do
  movie = Movie.create([{ name: Faker::Book.title,
                          director: Faker::Name.name,
                          description: Faker::FamilyGuy.quote,
                          year: rand(1920..2018),
                          length: rand(80..240),
                          format: formats[rand(formats.length)],
                          genre: genres[rand(genres.length)],
                          image: images[rand(images.length)],
                          thumbnail: images[rand(images.length)] }])
  unless movie.nil?
    rand(1..10).times do
      movie.comments.create(
        author: Faker::Name.name,
        title: Faker::Book.title,
        content: Faker::FamilyGuy.quote,
        rating: rand(1..5)
      )
    end
  end
  puts movie.inspect
end

这是我的评论模型:

class Comment < ApplicationRecord
  belongs_to :movie
end

这是我的电影模型:

class Movie < ApplicationRecord
  has_many :comments

  validates_presence_of :name, :director
#  validates_numericality_of :year, :length, greater_than: 0
  validates_uniqueness_of :name, message: 'Name is already used!'
#  validates_length_of :year, maximum: 4

  paginates_per 10

  def proper_name
    name.titleize
  end

end

感谢您的帮助。

我可以看到两个问题:

  1. Movie.create中,需要去掉方括号。那是因为 ActiveRecord create 方法需要一个哈希,而不是一个数组。当你这样做时,你也可以删除花括号,你的参数仍然会被识别为哈希。

  2. 检查 movie 是否为 nil 不是正确的测试,因为 movie 将始终存在,即使它没有保存到数据库。将测试从 unless movie.nil? 更改为 if movie.persisted? 这将避免因尝试将评论保存到未保存到数据库的电影而导致的错误。

因此您的代码应如下所示:

100.times do
  movie = Movie.create(name: Faker::Book.title,
                       director: Faker::Name.name,
                       description: Faker::FamilyGuy.quote,
                       year: rand(1920..2018),
                       length: rand(80..240),
                       format: formats[rand(formats.length)],
                       genre: genres[rand(genres.length)],
                       image: images[rand(images.length)],
                       thumbnail: images[rand(images.length)])
  if movie.persisted?
    rand(1..10).times do
      movie.comments.create(
          author: Faker::Name.name,
          title: Faker::Book.title,
          content: Faker::FamilyGuy.quote,
          rating: rand(1..5)
      )
    end
  end
  puts movie.inspect
end

为什么有些电影没有被保存?我怀疑您 运行 没有电影片名,然后没有满足您的唯一性约束。 Faker 对任何类别的回答都是有限的。我认为只有 22 个独特的 Faker::Book.title 回复。