2

I'm using Rails 3.1 and Backbone.js to create an application. Working with a collection of models, pulled from a database (via Rails controller) I am getting every attribute from the database to javascript. But with the same methods and code to do the same thing with another model and I'm not getting the database 'id' for the second model.

Here's the code that is working:

window.Post = Backbone.Model.extend
  urlRoot: '/posts'

  defaults:
    author_id: 2  

window.Posts = Backbone.Collection.extend
  model: Post
  url: '/posts'

Controller:

respond_to :html, :json, :js

def index
  @posts = current_user.posts
  respond_with(@posts.to_json(:include => {:account => {:only => :institution}}))
end

With this above I get a model with an attribute of id that is pulled from the database, but below does not contain the id attribute for the User model

And this is not:

window.User = Backbone.Model.extend
  urlRoot: '/members'

window.Users = Backbone.Collection.extend
  model: User
  url: '/members'

Controller:

respond_to :html, :json, :js

def index
  @users = @account.users
  respond_with(@users)
end
mu is too short
  • 426,620
  • 70
  • 833
  • 800
Sparkmasterflex
  • 1,837
  • 1
  • 20
  • 33

2 Answers2

1

try setting _id on your model. See here:

http://documentcloud.github.com/backbone/#Model-idAttribute

idAttribute model.idAttribute: A model's unique identifier is stored under the id attribute. If you're directly communicating with a backend (CouchDB, MongoDB) that uses a different unique key, you may set a Model's idAttribute to transparently map from that key to id.

when your model is returned from your database back to the app, backbone will see that key and automatically update your model.id. So for example, i use mongodb and have to set model.idAttribute = "_id".

Sneaky Wombat
  • 1,838
  • 2
  • 21
  • 29
0

Thank you for your help, this was the issue. Rails' to_json and/or respond_with(@user) was dropping the 'id' attribute. I found a solution to this via [link]http://stackoverflow.com/questions/3719041/how-to-customize-to-json-response-in-rails-3[link].

Basically I made a method 'as_json' in my model and made sure it returned a hash of attributes with my id included.

Sparkmasterflex
  • 1,837
  • 1
  • 20
  • 33