具有 mongoid 的命名空间模型

Namespace models with mongoid

这应该不会太难,但我没有找到任何答案。 尝试在文件夹中组织我的模型并使用 rails 和 mongoid 嵌入文档。

我的文件夹结构:

app/models/book.rb  Book
app/models/book/author.rb   Book::Author
app/models/book/author/bio.rb   Book::Author::Bio
app/models/book/author/interest.rb  Book::Author::Interest

我的模型classes:

class Book
    include Mongoid::Document
    include Mongoid::Timestamps
    belongs_to :user, inverse_of: :books
    embeds_many :authors
end
class Book::Author
    include Mongoid::Document
    include Mongoid::Timestamps
    belongs_to :book, inverse_of: :authors
    embeds_many :bios
end
class Book::Author::Bio
    include Mongoid::Document
    include Mongoid::Timestamps
    belongs_to :author, inverse_of: :bios
end
class Book::Author::Interest
    include Mongoid::Document
    include Mongoid::Timestamps
    belongs_to :author, inverse_of: :interests
end

当我这样做时:

book = Book.new
book.author

然后我得到uninitialized constant Author

使用 mongoid 7.0.1 和 rails 5.2

我尝试尝试使用结构、class 名称等,但我不确定我遗漏了什么。

根据@mu 的评论太短,如果它们不遵循约定,您需要指定 class_name 以及已定义的关联。这就是你如何让它发挥作用的方法:

class Book
  include Mongoid::Document
  embeds_many :authors, class_name: 'Book::Author'
end

class Book::Author
  include Mongoid::Document

  # `embedded_in` will suit this relation better
  embedded_in :book, inverse_of: :authors
  embeds_many :bios, class_name: 'Book::Author::Bio'
end

class Book::Author::Bio
  include Mongoid::Document
  embedded_in :author, class_name: 'Book::Author', inverse_of: :bios
end

class Book::Author::Interest
  include Mongoid::Document

  # I don't see a relation `interests` anywhere in your models
  belongs_to :author, class_name: 'Book::Author', inverse_of: :interests
end

但是,我有点疑惑,你为什么要这样存储它们。为什么一个作者会嵌入一本书中,因为一个作者可以拥有多本书?我会将结构更改为:

class Book
  include Mongoid::Document
  has_and_belongs_to_many :authors
end

class Author
  include Mongoid::Document
  has_and_belongs_to_many :books
  embeds_many :bios, class_name: 'Author::Bio'
  embeds_many :interests, class_name: 'Author::Interest'
end

class Author::Bio
  include Mongoid::Document
  embedded_in :author, inverse_of: :bios
end

# Not exactly sure what this model is for, so with limited information, i will keep it under namespace `Author`.
class Author::Interest
  include Mongoid::Document
  embedded_in :author, inverse_of: :interests
end