Search code examples
ember.jsrelationshiphas-manyrelationships

Add second model to a route


My application is for swimming lessons. I need to add swimmers to a class. The relationship is has many in both directions. A Lesson can have many Swimmers and Swimmers can have many Lessons.

From the lesson route, I would like to select a swimmer in a drop down, from a list of all swimmers and have an action add that swimmer's ID to the lesson's "swimmers" array.

I can't get the swimmers to show up in the drop down field because I don't think I am loading the second model correctly.

I would also be open to suggestions of how to add a specific swimmer to a specific class. It's important to see all available swimmers

I am new to both ember and programming so please keep this in mind when making suggestions. Thank you!

App.Router.map(function() {
this.resource('lessons', { path: '/lessons' }, function() {
  this.resource('lesson', { path: '/:lesson_id' })
  this.route('new', { path: '/new' })
});

this.resource('swimmers', { path: '/swimmers' }, function() {
  this.resource('swimmer', { path: '/:swimmer_id' })
  this.route('new', { path: '/new' })
});

});


App.Lesson = DS.Model.extend({

type: DS.attr(),
name: DS.attr(),
/*level: DS.attr(),   sometimes there are hybrid levels, likely leave it up to */
instructor:DS.belongsTo('instructor', {async: true}),
startDate: DS.attr(),
endDate: DS.attr(),
capacity: DS.attr('number'),
swimmers: DS.hasMany('swimmer',{async: true}),
});

App.Swimmer = DS.Model.extend({


  nameFirst: DS.attr(),
  nameLast: DS.attr(),
  level: DS.attr(),
  birthdate: DS.attr(),
  gender: DS.attr(),
  note:DS.attr(),
  lessons: DS.hasMany('lesson', {async: true}),
  });



 App.LessonRoute = Ember.Route.extend({
  model: function(params) {
      return Ember.RSVP.hash({
          lesson: this.store.find('lesson', params.lesson_id),
          swimmers: this.store.findAll('swimmer')
      })
   },

   setupController: function(controller, model) {
    controller.set('model', model.lesson);
    controller.set('swimmer', model.swimmer);
  },
});

Drop down I am trying to use

                    <div class="form-group">
                      <label for="lesson_swimmers" class="col-sm-2 control-     label">Swimmers</label>
                      <div class="col-sm-9">
                        {{view Ember.Select content=swimmers optionLabelPath="content.fullName" class="form-control" id="lesson_swimmers"}}
                      </div>
                    </div>

Solution

  • There are two answers to this question. The right one for you will depend on how you are providing the Model.

    If you are arriving via transferTo or linkTo you will need to use a different approach than if you are arriving directly via URL.

    @Kingpin2k answers the question and provides examples here,

    Kingpin2k's elegant solution.