Mongoid:如果可能,如何将父母分配给预先存在的孩子?

时间:2013-09-20 09:50:30

标签: sinatra mongoid

在模型定义中,您可以拥有多个belongs_to语句吗?如果答案是否定的,请继续阅读。我试图在sinatra应用程序中创建三个与mongoid的1-n引用关系。

模型

class SkillTrack
  include Mongoid::Document
  belongs_to :student
  belongs_to :grading_period
  belongs_to :teacher
end

class Student
  include Mongoid::Document
  field :name
  field :nickname
  field :dob, type: Date
  has_many :skill_tracks
end

class GradingPeriod
  include Mongoid::Document
  field :school_year
  field :period_name
  field :signing_date, type: Date
  has_many :skill_tracks
end

class Teacher
  include Mongoid::Document
  field :name
  has_many :skill_tracks
end

路由

post "/skill_track/new" do
  form = params[:formdata] # using sinatra form helpers gem
  student = Student.find("#{formdata["student_mongo_id"]}") 
  working = (student.skill_tracks.create).id
  ??? what do I do with working to make it a child of a teacher and of a grading_period?
end

我尝试了什么

mongoid docs对我来说最有希望的是:

band.member_ids = [ id ] #Set the related document ids.

我在irb中捣乱,并在我的模型中尝试了很多变化,但我无法为新创建的技能追踪对象设置父教师或评分期。学生外键在创建时设置正确。 我希望我有一个简单的语法无知,但我尝试了很多变化我想知道我是否可以做到这一点。

更新:

我只需要将work.save添加到David Troyer的答案和繁荣的工作中。

post "/skill_track/new" do
 form = params[:formdata]
 student = Student.find("#{formdata["student_mongo_id"]}") 
 working = student.skill_tracks.create
 working.teacher = Teacher.create # or find
 working.grading_period = GradingPeriod.create # or find
 working.save
end

1 个答案:

答案 0 :(得分:0)

我相信。如果我正确理解您的问题,请尝试在子SkillTrack文档上使用一些setter。

post "/skill_track/new" do
  form = params[:formdata]
  student = Student.find("#{formdata["student_mongo_id"]}") 
  working = student.skill_tracks.create
  working.teacher = Teacher.create # or find
  working.grading_period = GradingPeriod.create # or find
end

进一步深入了解您引用的mongoid docs操作部分