我有一个 PizzaType 模型,其中包含比萨的嵌套集合。比萨系列是根据比萨类型列出的。我希望能够单击比萨集合中的比萨并显示其属性。
动态设置 url 参数的最佳方法是什么?该 url 不需要导航到书签和共享的路由,只需检索特定资源。
我有它,如果有人想查看比萨饼类型,则 url 是pizza_type/:id
:id 是属于比萨饼类型(父模型)的 id
我目前有它,所以如果在 Pizzas Collection(属于 Pizza Type Model)中单击比萨,则不遵循比萨资源的路径;只是页面上的一个区域被更新。需要 url 路径,以便 jQuery 可以获取资源来更新该区域。Pizza 的 url 是pizza_types/:pizza_type_id/pizzas/:id
Here,:id
是 Pizza 模型的 id,:pizza_type_id
是 Pizzas 集合的成员共享的外键,用于将它们分组到集合中,属于 Pizzas 类型模型。
当我点击披萨(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"
}
]