嵌入式文档未添加

时间:2011-02-18 18:53:32

标签: ruby-on-rails-3 mongodb mongoid

添加嵌入文档时遇到问题。我正在尝试添加嵌入用户的标记。

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

不确定问题是什么或从哪里开始。它实际上看起来像是找到了用户,然后对标签进行了更新,但是没有成功。

由于

1 个答案:

答案 0 :(得分:1)

模型中的Tags类嵌入在用户内部(通过embeds_many关联),而不是自己的表。因此,在控制器中进行更新后,您应该具有以下内容:

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

使用MongoID,您还可以通过将“embeds_many”替换为“references_many”来将标记显示在自己的集合中。

在上面的评论中,您会看到问题berek-bryan与添加标记的位置有关。他希望将标签添加到自己的集合中,因此问题就出现了。实际上,标签正被添加到他的用户集合中。

相关问题