我用nokogiri收集的数据在ruby中创建了一个哈希数组。在我的一个名为[:contributors]的键中,我存储了另一个包含名字列表的数组。我已经验证了我的数据结构中的数据是正确的,并且工作正常。
我试图从我的seeds.rb文件中播种数据来填充我的PostgreSQL数据库,但由于某些原因,它只填充了[:contributors]的一半。下面是我用来迭代我的数据结构以创建种子数据的代码。
@trending_array.each_with_index do |item, index|
Repository.create(title: item[:title], description: item[:description], language:
item[:language])
item[:contributors].each do |contributor|
Contributor.create(username: contributor, repository_id: index + 1)
end
end
我所有的迁移都能正常进行 我的模型验证也是正确的。大约有一半的数据种子正确,所有的关联都能正常工作,但它总是在总共115qty的贡献者中的36qty之后停止。
有什么想法可以解释为什么我的整个数据集不能正常播种?
你分配数据的方式是 repository_id
是不正确的。当你第二次运行这个函数时会发生什么?索引字段总是从 0 开始,所以你的代码总是会寻找一个 id 为 1 的版本库。
所以每次你运行这个脚本时,尽管它正在创建新的仓库,但贡献者被分配到同一个仓库。贡献者都会被分配到相同的版本库中。如果你删除了前 115 个仓库记录,那么你的贡献者将不会被创建(因为它将尝试找到 id 1 的仓库)。
假设你的关联是正确的(Repository has_many Contributors)。
@trending_array.each do |item|
repository = Repository.create(title: item[:title], description: item[:description], language: item[:language])
repository.contributors.create(username: contributor)
这样就不需要id了,因为你是在使用你刚刚创建的仓库为该记录创建贡献者。
你的新块应该是这样的。
@trending_array.each do |item|
repository = Repository.create(title: item[:title], description: item[:description], language: item[:language])
item[:contributors].each do |contributor|
repository.contributors.create(username: contributor)
end
end
尝试使用 Repository.create!
和 Contributor.create!
而不是none-bang版本,所以如果有一个错误,它会被提出,你会得到一个错误的消息。
主要我想可能是验证的问题。Contributor
模型不合格,或 index+1
没有产生一个有效的 repository_id
.
非爆炸版本不会引发错误,只会返回 false
如果创建成功,则创建的记录。