2

我正在尝试使用 faker gem 播种数据,但我得到了一个非常奇怪的结果。类别使用 gem 填充,但文章不填充。我已经测试了在带有关联的数据库中输入数据,它工作正常。我运行时没有收到任何错误消息

耙分贝:种子

这是种子.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
4

0 回答 0