在Ember和Ember Data中转换时,URL中的“未定义”而不是ID

时间:2016-02-03 11:46:46

标签: ember.js ember-data ember-cli

我有一个非常标准的帖子模型,带有标题和文本字段。我有两条模型路线 - 新路线和展示路线。我想从新路线创建一个帖子,然后转换到show route。

这是我的路由器文件

this.route('post-new', { path: '/posts/new' });
this.route('post-show', { path: '/posts/:postId' });

submit控制器中的post-new操作就是这样的。

actions: {
  submit() {
    const { title, text } = this.getProperties('title', 'text');
    let post = this.store.createRecord('post', {
      title: title,
      text: text
    });
    post.save().then(() => {
      //success
      this.transitionToRoute('post-show', post);
    }, () => {
      //error
    });
  }
}

所以我希望将其从http://localhost:4200/posts/new重定向到类似http://localhost:4200/posts/23的内容(假设23是id)。
save()成功并在后端创建记录(这是rails),我还看到使用Ember Inspector在浏览器中更新post记录(现在它有ID)。但重定向发生在http://localhost:4200/posts/undefined

如何在保存后将其重定向到http://localhost:4200/posts/23之类的内容?

顺便说一下,版本是:
ember cli:2.3.0-beta.1
余烬:2.3.0
英国数据:2.3.3

更新

我能够通过替换此

来使其工作
this.transitionToRoute('post-show', post);

用这个

this.transitionToRoute('/posts/' + post.id);

但我希望找到一个使用路由名称而不是实际路径路径的解决方案。

2 个答案:

答案 0 :(得分:1)

尝试:

post.save().then(savedPost => {
  //success
  this.transitionToRoute('post-show', savedPost);
},

答案 1 :(得分:0)

您可以在路线上实施serialize挂钩。

serialize(model) {
  return { postId: model.get('id') };
}

如果您已经拥有模型,这将允许您避免调用模型钩子。因此,这两个都将按预期工作:

this.transitionToRoute('post-show', post);    // this will NOT call model() hook
this.transitionToRoute('post-show', post.id); // this will call the model() hook

API docs for Route中提供了更多信息。