Ruby on rails 3 Mongoid多对多关系问题添加记录
我正在将Mongoid/MongoDB与Rails一起使用,并试图建立多对多关系。基本上是书籍和类别,其中书籍可以分为多个类别。我一直收到一个错误:Ruby on rails 3 Mongoid多对多关系问题添加记录,ruby-on-rails-3,mongodb,mongoid,Ruby On Rails 3,Mongodb,Mongoid,我正在将Mongoid/MongoDB与Rails一起使用,并试图建立多对多关系。基本上是书籍和类别,其中书籍可以分为多个类别。我一直收到一个错误: undefined method `metadata' for "4e6aaec8ffb1900c19000002":String 尝试添加新书并将其分类时。下面是我对模型、表单、创建方法以及服务器报告的内容所使用的内容 看起来它正在尝试更新book_ID和cat_ID,但是没有得到任何关于cat_ID的信息。我已经尝试了很多不同的东西,但不知道
undefined method `metadata' for "4e6aaec8ffb1900c19000002":String
尝试添加新书并将其分类时。下面是我对模型、表单、创建方法以及服务器报告的内容所使用的内容
看起来它正在尝试更新book_ID和cat_ID,但是没有得到任何关于cat_ID的信息。我已经尝试了很多不同的东西,但不知道如何使这项工作
图书模型
class Book
include Mongoid::Document
field :title, :type => String
field :description, :type => String
has_and_belongs_to_many :cats
end
猫模型分类
class Cat
include Mongoid::Document
field :name, :type => String
field :description, :type => String
has_and_belongs_to_many :books
end
这来自生成类别选择并允许多个选择的表单:
<div class="field">
<%= label_tag "Cats" %><br />
<%= f.collection_select :cats, Cat.all, :id, :name, {}, :multiple => true %>
</div>
提交表单时从服务器发送:
Started POST "/books" for 127.0.0.1 at Fri Sep 09 17:30:37 -0700 2011
Processing by BooksController#create as HTML
Parameters: {"commit"=>"Create Book", "authenticity_token"=>"+OAIJM3NRPrUv0u1yfDEkkE2gvPQ7n0P6zPU9ZtqXlk=",
"utf8"=>"✓", "book"=>{"title"=>"The Golf & Tennis Book",
"cats"=>["4e6aaec8ffb1900c19000002", "4e6aaee8ffb1900c19000006"],
"description"=>"Both golf and tennis in this book, so it's in both categories."}}
MONGODB blog_development['system.namespaces'].find({})
MONGODB blog_development['cats'].update({:_id=>{"$in"=>[]}}, {"$pull"=>{"book_ids"=>BSON::ObjectId('4e6aafadffb1900c1900000b')}})
MONGODB blog_development['system.namespaces'].find({})
MONGODB blog_development['books'].update({"_id"=>BSON::ObjectId('4e6aafadffb1900c1900000b')}, {"$set"=>{"cat_ids"=>[]}})
Completed 500 Internal Server Error in 24ms
NoMethodError (undefined method `metadata' for "4e6aaec8ffb1900c19000002":String):
app/controllers/books_controller.rb:46:in `new'
app/controllers/books_controller.rb:46:in `create'
这是无效的
book.update_attributes({:cats => [ cat.id ]})
应该是这个吗
book.update_attributes({:cat_ids => [ cat.id ]})
或
好吧,我很尴尬。我发现我需要为集合中的第一个参数定义cat\u id\u select not use:cats,正如我所做的:
book.update_attributes({:cat_ids => [ cat.id ]})
book.update_attributes({:cats => [ cat ]})