在backbone.js我正在更新一个类别模型:
- @category.save {
- name : category_name,}
这样可以很好地保存并在骨干网中正确更新集合.但是在rails服务器上由于路由错误而无法保存:
- Started PUT "/categories" for 127.0.0.1 at 2011-05-24 11:18:16 -0400
- ActionController::RoutingError (No route matches "/categories"):
问题是rails希望PUT / update有一个包含id“/ categories /:id”的url,而不仅仅是“/ categories”
我通过更改模型URL来测试它:
- class Category extends Backbone.Model
- name: 'category'
- url: ->
- host + '/categories'
至
- class Category extends Backbone.Model
- name: 'category'
- url: ->
- host + '/categories/2'
这很好用.
- Started PUT "/categories/2" for 127.0.0.1 at 2011-05-24 11:44:08 -0400
- Processing by CategoriesController#update as JSON
- Parameters: {"category"=>{"created_at"=>2010-03-14 16:30:07 -0400,"id"=>2,"name"=>"Lunchr5","updated_at"=>2010-03-14 16:30:07 -0400,"user_id"=>1},"api_key"=>"s1boakDIav30V6DzOFsY","id"=>"2"}
- User Load (0.2ms) SELECT `users`.* FROM `users` WHERE `users`.`single_access_token` = 's1boakDIav30V6DzOFsY' LIMIT 1
- User Load (0.3ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
- sql (0.1ms) BEGIN
- AREL (0.3ms) UPDATE `users` SET `visit_count` = 11,`perishable_token` = 'YG3s4yB01FxUMdMcK8m',`updated_at` = '2011-05-24 15:44:08' WHERE `users`.`id` = 1
- sql (0.3ms) COMMIT
- Option Load (0.3ms) SELECT `options`.* FROM `options` WHERE (`options`.user_id = 1) LIMIT 1
- Category Load (0.2ms) SELECT `categories`.* FROM `categories` WHERE `categories`.`id` = 2 LIMIT 1
- sql (0.1ms) BEGIN
- Category Load (13.1ms) SELECT `categories`.`id` FROM `categories` WHERE `categories`.`user_id` = 1 AND (`categories`.`name` = BINARY 'Lunchr5') AND (`categories`.id <> 2) LIMIT 1
- AREL (0.3ms) UPDATE `categories` SET `name` = 'Lunchr5',`updated_at` = '2011-05-24 15:44:09' WHERE `categories`.`id` = 2
- sql (0.3ms) COMMIT
- Redirected to http://localhost:3000/categories
- Completed 302 Found in 179ms
我是否必须破解骨干以将:id添加到网址或我错过了什么?
解决方法
Backbone将根据Model.url()的结果确定要使用的url.所以,如果你有
- class Category extends Backbone.Model
- name: 'category'
- url: ->
- host + '/categories'
url骨干网的保存方法将在服务器上尝试:host’/ categories’
如果你没有定义url函数,url函数的默认行为将委托给它所在的集合.所以如果你有一个集合
- class Categories extends Backbone.Collection
- model:Category
- url: ->
- host + '/categories'
- class Category extends Backbone.Model
- name: 'category'
属于Categories集合的Category实例将自动使用url host’/ categories”/’category.id保存到服务器.
现在,如果您的模型不是集合的一部分,那么您不能这样做.您必须覆盖模型中的url函数,如下所示
- class Category extends Backbone.Model
- name: 'category'
- url: ->
- u = "#{host}/categories/"
- u = "#{u}#{this.id}" if this.id
- u
请注意,这不是黑客行为.这是正确使用骨干.实际上在未来的骨干版本中,我相信url函数没有默认行为,并且必须为所有模型编写url函数.