简体   繁体   中英

Add new record to model from different controller Ember.js

I have two controllers, and two models. (I have a third, groups , but that is of no matter in this situation.) My models are associated as such:

App.Favorite = DS.Model.extend({
    lodge: DS.belongsTo('lodge'),
    notes: DS.attr('string'),
    groups: DS.hasMany('group', {async:true}),
    photo: DS.attr('string'),
});
App.Lodge = DS.Model.extend({
    name: DS.attr('string'),
    address: DS.attr('string'),
    website: DS.attr('string'),
    phone: DS.attr('string'),
    uniqueDescription: DS.attr('string'),
    basicDescription: DS.attr('string'),
    yearOpened: DS.attr('string'),
    propertySize: DS.attr('string'),
    propertyType: DS.attr('string'),
    languages: DS.attr('string'),
    owner: DS.attr('string'),
    uniqueQualifier1: DS.attr('string'),
    uniqueQualifier2: DS.attr('string'),
    uniqueQualifier3: DS.attr('string'),
    uniqueQualifier4: DS.attr('string'),
    lowDayPrice: DS.attr('string'),
    highDayPrice: DS.attr('string'),
    favoriteBoolean: DS.attr('boolean')
});

From inside my lodge template I am attempting to "assign" that particular lodge to be a favorite. How then can I add a new favorite record to it's model, from the lodge controller? The Ember guides and API doesn't seem to have this use case, as far as I can tell.

Sample lodge controller:

App.LodgeController = Ember.ObjectController.extend({
    actions: {
        createFavorite: function() {
            // Not sure what to do here
            //
            // Create new record
            //
            // Then transition to newly created record route
        }   
    }
});

Routes:

App.Router.map(function() {
  this.resource('groups', { path: '/groups' });
  this.resource('group', {path: '/group/:group_id'});
  this.resource('favorites', {path: '/favorites'});
  this.resource('lodges', {path: '/'});
  this.resource('favorite', {path:'/favorite/:favorite_id'})
});

I think you should be able to do something like this in your createFavorite function:

var lodge = this.get('content');
var fav = this.store.createRecord('farvorite',{ lodge : lodge });
var _this = this;  // Inside didCreate 'this' will point to something different
fav.on('didCreate',function(){
  _this.transitionToRoute('favorite',fav);
});
fav.save();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM