mysql - 数据库 ID 未在 Rails 和 Backbone.js 之间传递

标签 mysql ruby-on-rails-3 json backbone.js

我正在使用 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/

相关文章:

php - 无法在 PHP 中解码 UTF8?

php - 使用 $_session 选择数据

mysql - 转换为 hh :mm:ss from days in sql

java - 使用 Camel Rest 时如何记录请求负载?

javascript - 将 CoffeeScript json 对象数据保存在 Rails 变量中

python - 如何解析日期(928142400000+0200)?

php - 给定用户名时,根据分数从无序的 MySql 数据库中获取排名

ruby-on-rails - 如何在 form_helper 中强制输入字段的 ID?

javascript - 轨道 3 jQuery : How to alert id of td

ruby-on-rails-3 - Bootstrap 添加的图标比 rails 中要求的要多