【发布时间】:2013-12-11 17:21:48
【问题描述】:
我正在查看来自http://www.backbonerails.com/ 的示例,它看起来完全一样。
让我从我的应用程序中为您画一张照片:
路线:
routes.rb:
Mario::Application.routes.draw do
root to: 'application#index'
resources :conferences
resources :participations, only: [:create]
end
控制器:
class ConferencesController < ApplicationController
respond_to :json
def show
@conference = Conference.find params[:id]
end
def index
@conferences = Conference.all
end
end
rbl 模板:
回复格式为index.json.rabl:
collection @conferences
attributes :id, :title
node(:date_from){|c| I18n.l c.date_from, format: :short}
node(:date_to){|c| I18n.l c.date_to, format: :short}
node(:lectures) do |c|
c.lectures_by_day.map do |l|
partial 'lectures/base', object: l
end
end
回复
这是我从http://localhost:3000/conferences.json得到的回复:
[
{
"id": 1,
"title": "Ruby on Rails for Dummies",
"date_from": "11 Dec 12:00",
"date_to": "13 Dec 17:00",
"lectures": []
}
]
骨干模型
这是应该从这里获取的 Backbone 模型:
@Mario.module "Entities", (Entities, App, Backbone, Marionette, $, _) ->
class Entities.Conference extends Backbone.Model
defaults:
title: ''
class Entities.ConferenceCollection extends Backbone.Collection
model: Entities.Conference
url: '/conferences.json'
...最后是 JS 控制台:
这就是我最终在 js 控制台中得到的结果:
cc=new Mario.Entities.ConferenceCollection()
▹ConferenceCollection {length: 0, models: Array[0], _byId: Object, constructor: function, model: function…}
cc.fetch()
此时,rails 服务器如此响应(来自log/development.log)
2013-12-11T18:07:55+01:00 [ INFO] 40497 : Started GET "/conferences.json" for 127.0.0.1 at 2013-12-11 18:07:55 +0100
2013-12-11T18:07:55+01:00 [ INFO] 40497 : Processing by ConferencesController#index as JSON
2013-12-11T18:07:55+01:00 [DEBUG] 40497 : Conference Load (0.2ms) SELECT "conferences".* FROM "conferences"
2013-12-11T18:07:55+01:00 [DEBUG] 40497 : (0.1ms) SELECT COUNT(*) FROM "lectures" WHERE "lectures"."conference_id" = 1 AND ("lectures"."date_from" BETWEEN '2013-12-11' AND '2013-12-12')
2013-12-11T18:07:55+01:00 [ INFO] 40497 : Rendered conferences/index.json.rabl (14.2ms)
2013-12-11T18:07:55+01:00 [ INFO] 40497 : Completed 200 OK in 20ms (Views: 18.3ms | ActiveRecord: 0.5ms)
回到 js 控制台:
cc.models[0]
▹Conference {cid: "c6", attributes: Object, collection: ConferenceCollection, _changing: false, _previousAttributes: Object…}
cc.models[0].attributes
▽attributes: Object
▹_byId: Object
▹_onModelEvent: function (event, model, collection, options) {
▹_prepareModel: function (attrs, options) {
▹_removeReference: function (model) {
▹_reset: function () {
▹add: function (models, options) {
▹all: function () {
▹any: function () {
▹at: function (index) {
▹bind: function (name, callback, context) {
▹chain: function () {
▹clone: function () {
▹collect: function () {
...
等等。等等 这些显然不是定义的模型属性。
到底发生了什么?这应该很简单。我一定错过了什么,但是什么?为什么 Backbone 没有将正确的 JSON 结构解释为模型的属性?
【问题讨论】:
-
是的,但
cc.models[0].attributes.models包含与cc.models[0]相同的对象,这意味着您可以无限期地执行cc.models[0].attributes.models[0].attributes等
标签: ruby-on-rails json backbone.js marionette rabl