我正在尝试使用faker gem来播种数据,我得到了一个非常奇怪的结果。使用gem填充类别,但不填充文章。我已经测试了在db中使用关联输入数据,它运行正常。我运行
时没有收到任何错误消息rake db:seed
这是seeds.rb文件。
# Create 8 seed categories
categories = Category.create([
{ name: 'History'}, {name: 'Biology'}, {name: 'Literature'},
{ name: 'Mathematics'}, { name: 'Music Theory'}, { name: 'Computer Science'},
{ name: 'Sociology'}, {name: 'Chemistry'}
])
# create 50 articles, with random titles, 250 words of content, and
# randomly assign one of the categories above to each article
for i in 0..49
title = Faker::Lorem.sentence(rand(2..10)).chomp('.')
content = Faker::Lorem.paragraph(word_count=250)
# randomly assign one of the categories we just created
category = Category.first(offset: rand(Category.count))
a = Article.create(title: title, content: content, categories: [category,])
end
同样,它可以创建类别,但不会创建文章。以下是db使用的所有模型。
class Article < ActiveRecord::Base
belongs_to :user
has_many :article_categories
has_many :categories, through: :article_categories
validates :title, presence: true
validates :content, presence: true
validates :categories, presence: true
end
class ArticleCategory < ActiveRecord::Base
belongs_to :article
belongs_to :category
validates :article_id, presence: true
end
class Category < ActiveRecord::Base
has_many :article_categories
has_many :articles, through: :article_categories
validates :name, presence: true
end