Markus
Markus

Reputation: 1214

ember (+ ember-auth) linkTo loggedIn user profile

To get straight to the point, I have an app with a profile accessible like that:

this.resource('user', {path: '/user/:user_id'});

This can accessed from visitors and (logged in users). Now I also have a menu-bar which has, only for logged in users, a link to the user-profile (so that would be /user/:loggedin-user_id). I am using ember-auth to authenticate the user and ember data for my models. The problem here seems to be {{linkTo 'user'}} doesn't work, because for one user that should link to /user/28, for the next one to /user/15. Simply to his/her own profile. I kinda get that it doesn't work, because how should ember know what ID to display (though yes, I don't understand the underlying reasons fully). Ember-Auth does provide App.Auth.get('userId') to get the Id of the currently logged in user, but I don't really know how I can tell ember to know that as well.

So what I had to do know is setting the link manually via

<a {{bindAttr href="App.loggedInUser"}}>

where-as this variable gets set to the right url in the Application controller with App.Auth.get('userId'). This works, but is obviously quite a hack.

Is there any 'ember' way of solving that?

Upvotes: 1

Views: 271

Answers (2)

heartsentwined
heartsentwined

Reputation: 306

ember-auth dev here.

Straight to solution:

First, ask ember-auth to load the user current user model. Assuming that your user model is called App.User, and it implements App.User.find(id).

App.Auth = Ember.Auth.create
  # ...
  userModel: 'App.User' # default null
  # pass the string, not a class App.User

# access the current user model
# as with all things ember, this is loaded asynchronously
App.Auth.get('user')

(copied from the docs.)

Next, pass this dynamic model to your handlebars links:

{{#linkTo 'user' App.Auth.user}}Link To Current User{{/link}}

Or otherwise - e.g. make it a binding to App.Auth.get('user'), etc.

Just in case, (js) App.get('foo') is equivalent to ember-handlebars App.foo.

Upvotes: 3

Darshan Sawardekar
Darshan Sawardekar

Reputation: 5075

Your user route has a dynamic segment. You can pass the user model to the linkTo and the anchor will point to that route for different users depending on the id of user model passed.

{{linkTo 'user' userObj}}Profile{{/linkTo}}

The model passed can be plain object with an id and the default serialization would still work. So if you wrap App.Auth.get('userId') into a object with an id you won't need a full model object.

Here's an example jsbin.

Upvotes: 0

Related Questions