在模型定义中,您可以拥有多个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
答案 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的操作部分