child records and ember model

安稳与你 提交于 2019-12-12 21:28:53

问题


[Update]

Thanks for the help so far.

I've been able to create a new Post record with an embedded Comment record with static data. Via this method:

    App.CommentsController = Ember.ArrayController.extend({
      needs: "post",

      actions: {

         addComment: function() {
              var post = App.Post.create({
                title: 'static post'
              });

                  post.get('comments').create({
                    message: 'static message'
                });

                  post.save();

          }

      }

    });

But I'm falling short figuring out how to retrieve the current Post via the CommentsController or Route in order to create Comment records on an already existing Post.

After searching and sifting through random SOs and articles, I've tried an array of methods to call the current Post but still no dice.

I've tried setting var post = App.Post.create to:

var post = App.Post.find(), 
var post = this.get('controllers.post.model'),
var post = this.get('controllers.post.content'),
var post = this.get('controllers.post'),
var post = this.get('post'),

I've also set my CommentsController to have needs: "post".

I've also tried adding:

    App.CommentsRoute = Ember.Route.extend({
        afterModel: function() {
            this.set('post', this.modelFor('post'));
        }
    });

I read a piece that stated actions should be defined in the routes as well, would I need to define my addComment function in the PostRoute?

I'm wondering if I need to use var post = App.Post.find(post) or something of that nature.

Am I on the right track here? Feels like I'm taking shots in the dark at an elephant in a broom closet and still missing...


回答1:


I use Ember-Model with built-in RESTAdapter, but should be compatible with your adapter:

// to add a post
var post = App.Post.create() // assuming your App.Post is your model class
// to add a comment inside it
var comment = post.get('comments').create()

To save, I use

post.save()

Since I am embedding the comments inside the post. If you're not, try call save() on comment object you've created:

comment.save()
post.save()



回答2:


try this

in the post controller when you save the record use this

post.save().then(function(post)     {self.transitionToRoute('comment.create', record);});

then in comments controller

 var post = this.get('comment').create();


来源:https://stackoverflow.com/questions/18772269/child-records-and-ember-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!