2011-09-10 46 views
1

我正在使用Mongoid/MongoDB与Rails,并试图获得多对多关系的工作。基本上可以分为多个类别的书籍和类别。我不断收到错误:Mongoid多对多关系问题添加记录

undefined method `metadata' for "4e6aaec8ffb1900c19000002":String 

试图添加新书并将其放入类别中时。以下是我用于模型,表单,创建方法和服务器正在报告的内容。

看起来它试图更新book_ids和cat_ids,但它没有为cat_ids获取任何东西。我一直在尝试很多不同的事情,但我不知道如何使这项工作。

书中模型

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> 

的在书籍控制器中创建方法:

def create 
    @book = Book.new(params[:book]) 
    redirect_to(@book, :notice => 'Book was successfully created.') 
end 

从服务器提交表单时:

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' 
+0

好吧,我很尴尬。我看到我需要为collection_select中的第一个参数定义cat_ids(不像以前那样使用:cats): <%= f.collection_select'cat_ids',Cat.all,... – Frank

回答

0

这是无效

book.update_attributes({:cats => [ cat.id ]}) 

应该是这个

book.update_attributes({:cat_ids => [ cat.id ]}) 

book.update_attributes({:cats => [ cat ]})