Getting Started with Ember.js Part 4: Creating a New Car


In the last post, we set up a show and edit view. Let’s set up a view that allows for adding new cars.

Getting Started with Ember.js

View on Github

This is a very similar process to adding the show route. Start by adding a new route to app/assets/javascripts/router.js. This time around we don’t have any parameters since this is a route that is creating and saving a new car.

Add a new route in app/assets/javascripts/routes/CarsRoutes.js. The model for this route is a new car record. On save Ember Data will post to /cars with a new car to create. Note that you also have to remove it from the client side store when leaving the page, otherwise you’ll end up with a blank car in the index grid. The call to rollback() in the deactivate function removes the car if the user decides to cancel. Once again you can transitionTo index or transitionTo the new car on the car.show route.

Finally, let’s add the template to app/assets/javascripts/templates/cars/new.js.hbs. This template is the same as the show template. I’ll leave it up to you to remove the duplication.

Upon trying to save the new car, you’ll notice that Ember throws a 404 while trying to post to /cars. We’ll have to head back over to the Rails side of things and set up a controller action to persist the new car.

Add a create method that saves the car and renders the new car’s JSON as a response. Once again, there is a fair bit of duplication here, so I’ll leave that up to you to solve. The controller in app/controllers/cars_controller.rb should look like this:

Finally, add an Add button to the index view in app/assets/javascripts/templates/cars/index.js.hbs

Now that you’ve got the ability to save a new car, head on to the final post Part 5: Deleting a Car and Wrapup.


Advertisement

No Comments

Name
A name is required.
Email
An email is required.
Site
Invalid URL

No comments yet