Search code examples
ember.jsember-cli

When creating a new data object in Ember that relies on another object how do you pass it along?


I am on a page where I can see a specific customer, part of my router.js is:

this.route('customers');
this.route('customer', {path: "customers/:customer_id"});
this.route('customer.order.create', { path: "customers/:customer_id/order/create" });

customer.order.create needs to load in my main view and so is not nested. An order 'has a' customer.

I've setup my /customer/order/create controller to have

needs: "customer"

I want to access the customer in my /customer/order/create.hbs template like this:

<h3>New Order for {{controllers.customer.name}}</h3>

When I end up creating the order I will also want to set newOrder.customer = customer.

customer.hbs links like so

<div>
  {{#link-to 'customer.order.create' model}}Create Order{{/link-to}}
</div>

Currently {{controllers.customer.name}} renders nothing, what piece of the puzzle am I missing to get to the customer in my order/create route?

Or putting it more generally, what route/controller/etc code do I need when I have a parent object which belongs to my child object in a /parentObject/parent_id/childObject/create type scenario.


Solution

  • There are many points to fix:

    1) {{controllers.customer}} is Controller Object, {{controllers.customer.name}} it's name property. I think you want {{controllers.customer.model.name}}.

    2) "..newOrder.customer = customer.." should be

     newOrder.set('customer', this.get('controllers.customer.model'));
    

    3) your customer.order.create route model hook shoudn't be empty, since you are using dynamic segment customer_id:

    //route
    model: function(params) {
      return this.find('customer', params.customer_id);
    }
    

    4) Your routes are not nested, so {{controllers.customer.model.name}} would be empty if your customer route is not activated. So you should use: {{model.name}} instead of {{controllers.customer.model.name}}

    When you click link you passes model directly, and model hook is not fired, so all looks good. When you visit url directly, model hook is fired. If it is empty you will see nothing.

    General concept: it is dependancy injection concept, you could read here: http://guides.emberjs.com/v1.12.0/understanding-ember/dependency-injection-and-service-lookup/