digitalpixelpro
digitalpixelpro

Reputation: 139

Can't access id on Backbone model on rails?

Problem: I am mirroring resourceful models in Rails with Backbone.js.I'm trying to get the current user id to a Backbone Workshop.Models.User model so I can save the user to the database through the Rails users RESTful resource. I can't retrieve the id from the Currentuser model. ?

I my return value is undefined when I try to retrieve the id of an instance of the current user model in Backbone. I can see on the server log that the fetch is successful and I can inspect the object if I output the local instance into the log. I can even use the console to run the same code and successfully get the id. It's only at runtime.

I suspect I'm supposed to configure my models differently or bind something in my view. Help?

See my gist here

Models:

# singleton model gets current user

class Workshop.Models.Currentuser extends Backbone.Model
idAttribute: '_id'
urlRoot: -> '/user/currentuser/'

# classic Rails RESTful resource

class Workshop.Models.User extends Backbone.Model
urlRoot: '/users/show'

Upvotes: 0

Views: 166

Answers (1)

timDunham
timDunham

Reputation: 3318

in your gist, you have the following code

current_user = new Workshop.Models.Currentuser
current_user.fetch()
console.log(current_user.id)

however, fetch is asnychronous and the id won't be filled in until the ajax call is done.

Try this (apologize because my ruby skills are zero and my coffeescript is not so good either so no guarantee on syntax)

current_user.fetch({ success: -> console.log(current_user.id) });

Upvotes: 5

Related Questions