简体   繁体   中英

Creating and Storing a Record with ember-data

I've set up the following model:

App.Store = DS.Store.extend({adapter: DS.FixtureAdapter});
App.store = App.Store.create();
App.Proposal = DS.Model.extend({
    title: DS.attr('string'),
    description: DS.attr('description')
});
App.Proposal.FIXTURES = [...];

That works great, and my app pulls out my fixture data and sets it all up. I can move around my app without issues.

Since displaying data works, I created a route to create a new Proposal. I can't figure out how to save it back to my data store though, and I think I'm doing everything correctly. Here's what I'm doing:

App.ProposalsNewController = Ember.ObjectController.extend({
    newRecord: function() {
        this.set('content', App.Proposal.createRecord());
    },
    actions: {
        saveNewProposal: function() {
            var newProposal = App.Proposal.createRecord({...});
            newProposal.save();
            this.transitionToRoute('proposals.index');
        }
    }
});

App.ProposalsNewRoute = Ember.Route.extend({
    setupController: function(controller) {
        controller.newRecord();
    }
}

When newProposal.save() is called, nothing appears in the datastore. My other concern is that most of the documentation says I should use this.store instead of App.Proposal when creating the record, but then that generates the following error:

TypeError: Object proposal has no method '_create'

What is the proper way to create and save a record? Or is it just because I'm using the FixtureAdapter?

You are indeed using a fairly old version of Ember Data.

Here's a quick example of Ember with a 1.0 beta version of ED.

http://emberjs.jsbin.com/OxIDiVU/73/edit

Here's some basic concepts that you'll need to change:

You don't need to create the store anymore, you create adapters

Application wide adapter

App.ApplicationAdapter = DS.RESTAdapter;

Model specific adapter

App.ColorAdapter = DS.FixtureAdapter;

Model creation/finding

Creating a model (from a route/controller)

this.get('store').createRecord('color', {name: 'green'});

Finding a model (from a route/controller)

this.get('store').find('color'); //find all of the colors

this.get('store').find('color', 1); //find color id 1

You'll want to glance over the Ember Data transition, which will be published as soon as they actually go to ED 1.0. That's why the documentation is so out of date.

https://github.com/emberjs/data/blob/master/TRANSITION.md

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