我正在关注Ruby and MongoDB Web Development一书,并尝试尽可能多地遵循这些示例,但由于某些原因,我无法使其正常工作。
这是我到目前为止所拥有的模型:
应用程序/模型/book.rb
class Book
include Mongoid::Document
field :title, type: String
field :publisher, type: String
field :published_on, type: Date
field :votes, type: Array
belongs_to :author
has_and_belongs_to_many :categories
embeds_many :reviews
end
应用程序/模型/作者.rb
class Author
include Mongoid::Document
field :name, type: String
has_many :books
end
应用程序/模型/category.rb
class Category
include Mongoid::Document
field :comment, type: String
field :username, type: String
has_and_belongs_to_many :books
end
到目前为止一切顺利,然后在 Rails 控制台中
irb(main):001:0> b = Book.new(title: "Oliver Twist", publisher: "Dover Publications", :published_on => Date.parse("2002-12-30"))
=> #<Book _id: 53c9215c456d655abb000000, title: "Oliver Twist", publisher: "Dover Publications", published_on: 2002-12-30 00:00:00 UTC, votes: nil, author_id: nil, category_ids: nil>
irb(main):002:0> Category.create(name: 'Fiction')
=> #<Category _id: 53c92161456d655abb010000, name: "Fiction", book_ids: nil>
irb(main):004:0* Category.create(name: 'Drama')
=> #<Category _id: 53c92166456d655abb020000, name: "Drama", book_ids: nil>
irb(main):005:0> b.categories << Category.first
=> [#<Category _id: 53c92161456d655abb010000, name: "Fiction", book_ids: [BSON::ObjectId('53c9215c456d655abb000000')]>]
irb(main):006:0> b.categories << Category.last
=> [#<Category _id: 53c92161456d655abb010000, name: "Fiction", book_ids: [BSON::ObjectId('53c9215c456d655abb000000')]>, #<Category _id: 53c92166456d655abb020000, name: "Drama", book_ids: [BSON::ObjectId('53c9215c456d655abb000000')]>]
irb(main):007:0> b.save
=> true
irb(main):008:0> b
=> #<Book _id: 53c9215c456d655abb000000, title: "Oliver Twist", publisher: "Dover Publications", published_on: 2002-12-30 00:00:00 UTC, votes: nil, author_id: nil, category_ids: [BSON::ObjectId('53c92161456d655abb010000'), BSON::ObjectId('53c92166456d655abb020000')]>
irb(main):009:0> Category.first
=> #<Category _id: 53c92161456d655abb010000, name: "Fiction", book_ids: nil>
irb(main):010:0>
类别对象没有更新,发生了什么?我做错了什么?帮助!
信息: Rails 4, Mongoid 4, Ruby 2.1, MongoDB 2.6
编辑1:
行embedded_in :book
从文件app/models/category.rb 中删除了不必要的行。