我正在构建一个简单的脚本来填充MongoDB数据库。这是我第一次使用NoSQL DB,我觉得我可能从SQL DB的角度考虑这个问题。
此脚本的基础是填充一个数据库,该数据库包含一些彼此相关的集合。但是,当我运行脚本时,在构建/保存文档时看到无效错误。
我有三个收藏; Book
,Author
和Style
具有以下关系。
Book
有很多Authors
Author
有很多Books
Author
有很多Styles
Style
有很多Authors
模型定义如下:
# Book Model
class Book
include Mongoid::Document
include Mongoid::Timestamps
field :title, type: String
validates :title, presence: true
has_and_belongs_to_many :authors
index({ title: 'text' })
end
# Author Model
class Author
include Mongoid::Document
include Mongoid::Timestamps
field :name, type: String
validates :name, presence: true
has_and_belongs_to_many :books
has_and_belongs_to_many :styles
index({ name: 1 }, { unique: true })
end
# Style Model
class Style
include Mongoid::Document
include Mongoid::Timestamps
field :type, type: String
validates :type, presence: true
has_and_belongs_to_many :authors
index({ type: 1 }, { unique: true, name: "type_index" })
end
然后这是我的脚本:
# script.rb
book = Book.new
book.title = "Good Omens"
['Neil Gaiman', 'Terry Pratchett'].each do |author_name|
author = Author.find_by(name: author_name)
if author.nil?
author = Author.new(name: author_name)
end
# a list of writing styles this author can have
# pretend that there's a list of styles per author
literary_styles.each do |style_name|
style = Style.find_by(type: style_name)
if style.nil?
author.styles.build(Style.new(type: style_name))
else
unless author.styles.include? style.id
author.styles << style
end
end
end
author.valid? #=> false
author.errors #=> @messages={:styles=>["is invalid"]}
book.author.build(book.attributes)
book.save
end
Book
文档已创建,但由于无效的样式验证错误,Author
和Style
无法持久保存。我希望我能确切看到导致验证失败的原因,但是消息非常模糊。我怀疑它是来自has_and_belongs_to_many
和Author
之间的Style
关系的一些内置验证,但我不能对此投入手指。
[我发现有趣的是Book
文档具有一个author_ids
属性,其中填充有id,但是当我跳入控制台时,没有任何作者可以被拉到或绑在Book
上。] >
如果需要,愿意提供更多信息。
我正在构建一个简单的脚本来填充MongoDB数据库。这是我第一次使用NoSQL DB,我觉得我可能从SQL DB的角度考虑这个问题。该脚本的基础...
我想我需要了解更多信息,才能明确地告诉您问题出在哪里-您使用的是哪个版本的Mongoid?您是在空数据库上运行此脚本,还是“作者”和“样式”文档已经存在?那些看起来像什么?