0
votes

I have a pretty standard post model with a title and a text field. I have two routes for the model -- new route and show route. I want to create a post from new route and then transition to show route.

This is my router file

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

and submit action in post-new controller is something like this.

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
    });
  }
}

So I am expecting this to redirect from http://localhost:4200/posts/new to something like http://localhost:4200/posts/23 (assuming 23 is id).
The save() is successful and record is created on the backend (which is rails) and I also see the post record updated in browser (it now has an ID) using Ember Inspector. But the redirection is happening to http://localhost:4200/posts/undefined.

How can I make this to redirect to something like http://localhost:4200/posts/23 after save ?

Btw, The versions are:
ember cli : 2.3.0-beta.1
ember : 2.3.0
ember data : 2.3.3


UPDATE

I was able to make it work by replacing this

this.transitionToRoute('post-show', post);

with this

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

But I am hoping for a solution using the route name and not actual route path.

2
Why don't you try: this.transitionToRoute('post-show', post.id);ashfaq.p
Asfaik dynamic segments are underscored :post_idPatsy Issa

2 Answers

1
votes

Try:

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

You can implement the serialize hook on your route.

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

This will allow you to avoid calling the model hook if you already have the model. So, both of these will work as expected:

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

More information available in the API docs for Route.