我有一个PizzaType模型,它有一个嵌套的Pizzas集合。比萨饼系列是根据比萨饼类型列出的。我希望能够点击比萨饼系列中的比萨饼并显示其属性。
动态设置url参数的最佳方法是什么? 该网址不需要导航到书签和共享的路径,只需要检索特定资源。
我知道如果有人想查看比萨饼类型,网址是pizza_type/:id
:id是属于Pizza Type(父模型)的id
我目前拥有它,如果在Pizzas Collection(属于Pizza Type Model)中点击披萨,则不会遵循披萨资源的路径;只更新页面上的某个区域。需要url路径,因此jQuery可以获取更新该区域的资源。披萨的网址是pizza_types/:pizza_type_id/pizzas/:id
这里,:id
是属于披萨模型的ID,而:pizza_type_id
是Pizzas Collection成员共享的外键以将其分组到该系列属于比萨饼型号。
当我点击披萨(id = 3)时,我得到"NetworkError: 404 Not Found - http://localhost:3000/pizza_types/3/pizzas"
以下是型号和收集代码:
@Pizzeria.module "Entities", (Entities, App, Backbone, Marionette, $, _) ->
class Entities.PizzaType extends Backbone.Model
urlRoot: "pizza_types/"
# creates the nested collection
initialize: ->
@pizzas = new Entities.PizzasCollection
@pizzas.url = @urlRoot + @id + '/pizzas'
@pizzas.fetch
reset: true
parse: (response) ->
response
class Entities.PizzaTypesCollection extends Backbone.Collection
model: Entities.PizzaType
url: 'pizza_types'
parse: (response) ->
response
# Is there a way to pass in a :pizza_type_id and :id params to pass to the url() so
# that the specific pizza model can be retrieved from the collection?
class Entities.Pizza extends Backbone.Model
url: -> "pizza_types/" + 2 + "/pizzas/" + 4 # <-- Hard coded works, but how to set the params dynamically?
parse: (data) ->
data
class Entities.PizzasCollection extends Backbone.Collection
model: Entities.Pizza
url: 'pizzas'
parse: (data) ->
data
有什么建议吗?这是正确的方法,我也尝试这样做:
class Entities.Pizza extends Backbone.Model
urlRoot: -> "pizza_types"
# I thought I could pass these params in and fetch the correct pizza model, but not working.
fetch
pizza_type_id: pizza_type_id
id: id
reset: true
parse: (data) ->
data
具有示例数据的PizzaType属性:
PizzaType: {
id: 2,
name: "Gourmet",
pizzas: [
0: {
id: 4,
pizza_type_id: 2
name: "gourmet pizza 1"
},
1: {
id: 5,
pizza_type_id: 2,
name: "gourmet pizza 2"
}
]
答案 0 :(得分:0)
对于披萨模型中的网址,您可以在初始化函数中为模型指定类似pizza_type的属性,并像这样更改网址功能
class Entities.Pizza extends Backbone.Model
initialize: (options)->
@pizza_type = options.pizza_type if options.pizza_type
url: ->
"pizza_types/" + @pizza_type + "/pizzas/" + @id
parse: (data) ->
data
class Entities.PizzaType extends Backbone.Model
urlRoot: "pizza_types/"
url: ->
@urlRoot+@id+'/pizzas' if @id
initialize: ->
@pizzas = new Entities.PizzasCollection
@pizzas.fetch reset: true
parse: (response) -> response
在PizzasCollection
中添加addOptions,以便在将模型添加到集合时,然后使用此默认选项添加主干
class Entities.PizzasCollection extends Backbone.Collection
model: Entities.Pizza
addOptions:
'pizza_type': @id
url: 'pizzas'
parse: (data) -> data
"NetworkError: 404 Not Found - http://localhost:3000/pizza_types/3/pizzas"
这是您的服务器的问题,可能是错误输入,或者是斜线问题或任何服务器问题。
P.S:我建议使用关系模型(任何插件都可以像BackboneRelationals那样)