Search code examples
ember.jsember-cli

Reuse ember controller for two routes, but pre populate part of model on one of the routes


Lets say we were modelling repositories in an app. We would want to be able to see all of our repo's at /repos/.

We can create a repo at /repos/create. In our model a repo has a owner (user), going down this route I would want my first form field in my create.hbs template to be selecting a user.

But it may also make sense to create a repo through viewing a user at /users/userId/repos, and then perhaps the route being /users/userId/repos/create. The difference here would be that the first field of my form would have the user pre populated.

I know that I can reuse the same controller by specifying this in my route:

controllerName: 'repos/create'

(what would the ember generate statement/ the place to put this route in my folder structure be, for this complex route?)

But how would I pass in the user to the repos/create controller?


Solution

  • The comment by @Artych provided the best way to do this currently, so to expand on this.

    In the end I created a repo-create component that may or may not be passed a user object. The logic for handling what to pre-populate can then be set in the logic of the component itself.

    After this is was simply a case of having a one line template at both /repos/create.hbs and /user/repos/create.hbs, with the component.

    I then followed the approach of using my user as my model in the routes/user/repos/create.js route and passing it to the component in my template as

    {{repo-create user=model}}
    

    With this approach I avoided doing anything explicitly on controllers, and moving up to Ember 2.x will be alot less painful.