Note that there are some explanatory texts on larger screens.

plurals
  1. POMongoid: If possible, how to assign a parent to pre-existing child?
    primarykey
    data
    text
    <p>In a model definition can you have more than one belongs_to statement? If the answer is no, read no further. I am trying to create three 1-n referenced relationships with mongoid in a sinatra app. </p> <h1>models</h1> <pre><code>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 </code></pre> <h1>routes</h1> <pre><code>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 </code></pre> <h1>what I have tried</h1> <p>The thing that looked the most promising to me from the <a href="http://mongoid.org/en/mongoid/docs/relations.html#has_many" rel="nofollow">mongoid docs</a> was:</p> <pre><code>band.member_ids = [ id ] #Set the related document ids. </code></pre> <p>I mucked about in irb and tried lots of variations in my models but I could not set a parent teacher or grading period for the newly created skilltracking object. The student foreign key was set properly on creation. I am hoping I have a simple syntax ignorance, but I tried so many variations I wonder if I can do this at all. </p> <h1>UPDATE:</h1> <p>I just needed to add working.save to David Troyer answer and boom working.</p> <pre><code>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 </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload