Mongomapper嵌入文档“无法序列化对象”错误

时间:2011-11-22 12:35:56

标签: ruby mongodb sinatra mongomapper

我对mongodb很新,我正在使用sinatra和mongomapper通过以下设置更新嵌入文档的值:

class TeamMember
  include MongoMapper::Document

  key :name, String, :required => true

  many :team_member_projects
end

class TeamMemberProject
  include MongoMapper::EmbeddedDocument

  key :date, Date, :required => true

  one :project 
end

class Project
  include MongoMapper::Document

  key :name, String, :required => true
end

修饰符代码为:

team_member = TeamMember.find(params[:team_member])
project = Project.find(params[:project])
date = Date.parse(params[:date])

tm_project = TeamMemberProject.new(:project => project, :date => date)
team_member.push(:team_member_projects => tm_project)
team_member.save

但我收到了.push行的错误:

BSON::InvalidDocument at /project/add
Cannot serialize an object of class TeamMemberProject into BSON.

我没有正确声明我的嵌入式文档吗?或者是否有另一种更新嵌入式文档的方法,我不知道。我正在尝试使用:http://mongomapper.com/documentation/plugins/modifiers.html#push

1 个答案:

答案 0 :(得分:1)

这似乎有效

team_member = TeamMember.find(params[:team_member])
project = Project.find(params[:project])
date = Date.parse(params[:date])

tm_project = TeamMemberProject.new(:project_id => project.id, :date => date)
team_member.team_member_projects << tm_project
team_member.save

好像我必须使用project.id。不知道为什么。也不确定为什么我的.push不起作用,因为我认为它与<<的作用相同。