2013-03-20 59 views
0

无法保存或创建新记录我试图用emberjs创建一个简单的博客应用程序。为这个帖子创建标题和正文的功能可以很好地工作,如此处所示jsfiddleemberjs无法使用emberjs-1.0.0-rc.1和ember-data修订版-11

现在我想添加下一个功能,这是注释,当您单击某个帖子时应该显示该功能。在主页上点击帖子,然后点击个人的标题,应该显示评论框以添加评论。

我收到以下错误,当我点击使用余烬数据,其余适配器保存按钮

在我的本地开发环境,我得到的错误:

uncaught TypeError: Cannot call method 'commit' of undefined 

在JSfiddle中使用具有相同代码的灯具适配器,错误变为

TypeError: this.transaction is undefined this.transaction.commit(); 

帖子/ show.handlebars

<script type="text/x-handlebars" data-template-name="posts/show"> 
     <h1>Post</h1> 
     <p>Your content here.</p> 
     <h3> {{title}} </h3> 
     <h3> {{body}} </h3> 
    </br> 
    <p> {{#linkTo 'posts.index'}} back {{/linkTo}}</p> 
    <p> {{#linkTo 'posts.edit' content}} Edit the post {{/linkTo}}</p> 
    <br/> 
    <p> Add Comments</p> 
     {{render 'comment/new' comments}} 
    </script> 

评论/ new.handlebars

<form {{action save on='submit'}}> 
    {{view Ember.TextArea valueBinding='body' placeholder='body'}} 
    <button type="submit"> Add comment </button> 
</form> 

    EmBlog.CommentNewController = Em.ObjectController.extend({ 
    needs: ['posts'], 
    addComment: function(){ 
     post = this.get('controllers.postsShow').get('model'); 
     comment = post.get('comments') 
     this.transaction = comment.get('store').transaction.createRecord({body: body}); 
    }, 

    save: function(){ 
     this.transaction.commit(); 
    } 
    }); 

EmBlog.Comment = DS.Model.extend({ 
    body: DS.attr('string'), 
    post_id: DS.attr('integer')' 
    post: DS.belongsTo('EmBlog.Post') 
}); 

如何在方式,每次我创建注释时,它将包括POST_ID解决这个问题的任何建议。

**Update** 

这是latest gist,当我保存评论,但评论不会出现在网页上不显示任何错误。看起来他们被默默地忽略了。

回答

2

DS.Store#transaction是一个函数,而不是一个属性。它返回一个DS.Transaction ...但是,您立即打电话给createRecord,所以您实际上将该调用的结果(记录)存储在您的事务属性中。此外,DS.Transaction上的createRecord需要一个类型作为第一个参数。

因为这是一个ObjectController,所以我们必须在我们的类定义中定义我们的内部属性,否则它们会传递给内容。

EmBlog.CommentNewController = Em.ObjectController.extend({ 
    transaction: null, 

然后在你的实际代码:

var transaction = post.get('store').transaction(); 
if (transaction) { 
    this.set('transaction', transaction); 
    transaction.createRecord(EmBlog.Comment, {body: body}); 
} else { console.log('store.transaction() returned null'); } 

再后来:

this.get('transaction').commit(); 

注意,注释不会自动作用域为Post,所以一定要设定你的关系。

+0

非常感谢@christopher的帮助。我用上面的代码片段替换了我的jsfiddle的相关部分,但它仍然返回了一个新的错误** TypeError:this.transaction未定义**。感谢您的任何新建议 – brg 2013-03-20 18:14:23

+0

因为您使用的是objectController,控制器会尝试在其内容上设置该属性。您需要在定义控制器时将'transaction'定义为控制器上的一个属性。 – 2013-03-20 18:30:09

+0

谢谢@christopher。我将'transaction'定义为控制器上的一个属性,并且有此错误。当我在控制器中将它定义为**事务时:'**,它返回错误:** TypeError:this.transaction.commit不是函数**。但是,当它被定义为 ** transaction:null **时,它将返回错误:** TypeError:this.transaction为null ** – brg 2013-03-20 18:53:41