【问题标题】:Mongoid: If possible, how to assign a parent to pre-existing child?Mongoid:如果可能,如何将父母分配给预先存在的孩子?
【发布时间】:2013-09-20 09:50:29
【问题描述】:

在模型定义中可以有多个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 中搞砸了,并在我的模型中尝试了很多变化,但我无法为新创建的技能跟踪对象设置家长老师或评分期。学生外键在创建时已正确设置。 我希望我有一个简单的语法无知,但我尝试了很多变体,我想知道我是否可以做到这一点。

更新:

我只需要将 working.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

【问题讨论】:

    标签: sinatra mongoid


    【解决方案1】:

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

    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操作部分

    【讨论】:

    • Working.teacher 没有方法错误。我需要语法方面的帮助。我觉得设置字段和设置外键不一样。
    • 通常我讨厌 RTFM 的答案,因为我总是先阅读。 Mongoid 文档过于简洁,恕我直言。
    • 话虽如此,我确实从您的回答中得到了帮助,因为它强化了我最初的感觉,它应该那么容易。在 irb 中这样做是有效的。在我添加 work.save 之前,在 sinatra 中执行此操作无效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-17
    • 1970-01-01
    相关资源
    最近更新 更多