2011-02-18 55 views
0

無法添加嵌入式文檔。我正在嘗試添加嵌入用戶的標籤。未添加嵌入式文檔

user.rb

class User 
    include Mongoid::Document 
    field :name 

    validates_presence_of :name 
    validates_uniqueness_of :name, :email, :case_sensitive => false  
    attr_accessible :name, :email, :password, :password_confirmation 

    embeds_many :tags 
    embeds_many :tasks 

    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable 
end 

tag.rb

class Tag 
    include Mongoid::Document 
    field :name 
    embedded_in :user, :inverse_of => :tags 
    references_many :tasks 
end 

tags_controller.rb

def create 
    #@user = User.find(:first, :conditions => {:_id => "4d3ae09bf5c4930b2b000004"}) 
    @user = current_user 
    @tag = Tag.new(params[:tag]) 

    @user.tags << @tag 
    @tag.save 

    redirect_to @tag, :notice => "Tag created!" 
    end 

這是輸出到服務器時,我嘗試創建一個新的標籤。

Started POST "/tags" for 127.0.0.1 at 2011-02-18 13:46:03 -0500 
Processing by TagsController#create as HTML Parameters: {"utf8"=>"✓", "authenticity_token"=>"6p+Jova7Hol2v5LRReSp2fhNJ967EwkeIzAWyrChQRE=", "tag"=>{"name"=>"general"}, "commit"=>"Create Tag"} 
db['users'].find({:_id=>BSON::ObjectId('4d39cd63f5c4930708000001')}, {}).limit(-1) MONGODB 
db['users'].update({"_id"=>BSON::ObjectId('4d39cd63f5c4930708000001')}, {"$push"=>{"tags"=>{"name"=>"general", "_id"=>BSON::ObjectId('4d5ebe6bf5c493554d000002')}}}) Redirected to 
http://localhost:3000/tags/4d5ebe6bf5c493554d000002 Completed 302 Found in 5ms 

不確定是什麼問題或從哪裏開始。它實際上看起來像用戶被發現然後正在對標籤進行更新,但它不成功。

感謝

+0

更新命令看起來不錯...控制器完成後用戶文檔的外觀如何? mongodb.log中是否顯示錯誤? – jared 2011-02-19 00:34:28

回答

1

模型中的標籤類嵌入的用戶裏面(通過embeds_many協會),而不是其自身的表。所以,按照您的控制器更新,你應該有這樣的事情:

> db.users.find() 
{ 
    _id: ObjectId('4d39cd63f5c4930708000001'), 
    tags: [ 
     { 
      _id: ObjectId('4d5ebe6bf5c493554d000002'), 
      name: "General" 
     } 
    ] 
} 

使用MongoID,你也可以有標籤與「references_many」代替「embeds_many」出現在自己的收藏。

在上面的註釋中,您會看到berek-bryan問題與添加標籤的位置有關。他預計該標籤將被添加到自己的收藏中,因此也是一個問題。實際上,這些標籤正被添加到他的用戶集合中。