我正在使用 Rails 3.1 和 Backbone.js 创建一个应用程序。使用从数据库中提取的模型集合(通过 Rails Controller ),我将数据库中的每个属性都获取到 javascript。但是用相同的方法和代码对另一个模型做同样的事情,我没有得到第二个模型的数据库“id”。
这是有效的代码:
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
通过上面的代码,我得到了一个模型,该模型具有从数据库中提取的 id 属性,但下面不包含用户模型的 id 属性
这不是:
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
最佳答案
尝试在您的模型上设置 _id。看这里:
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.
当您的模型从数据库返回到应用程序时,backbone 将看到该 key 并自动更新您的 model.id。因此,例如,我使用 mongodb 并且必须设置 model.idAttribute = "_id"。
关于mysql - 数据库 ID 未在 Rails 和 Backbone.js 之间传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10129265/