ruby-on-rails – 使用Backbone.js更新模型Rails无法正常工作(未找到PUT路由)

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 使用Backbone.js更新模型Rails无法正常工作(未找到PUT路由)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在backbone.js我正在更新一个类别模型:
  1. @category.save {
  2. name : category_name,}

这样可以很好地保存并在骨干网中正确更新集合.但是在rails服务器上由于路由错误而无法保存:

  1. Started PUT "/categories" for 127.0.0.1 at 2011-05-24 11:18:16 -0400
  2.  
  3. ActionController::RoutingError (No route matches "/categories"):

问题是rails希望PUT / update有一个包含id“/ categories /:id”的url,而不仅仅是“/ categories”

我通过更改模型URL来测试它:

  1. class Category extends Backbone.Model
  2. name: 'category'
  3. url: ->
  4. host + '/categories'

  1. class Category extends Backbone.Model
  2. name: 'category'
  3. url: ->
  4. host + '/categories/2'

这很好用.

  1. Started PUT "/categories/2" for 127.0.0.1 at 2011-05-24 11:44:08 -0400
  2. Processing by CategoriesController#update as JSON
  3. 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"}
  4. User Load (0.2ms) SELECT `users`.* FROM `users` WHERE `users`.`single_access_token` = 's1boakDIav30V6DzOFsY' LIMIT 1
  5. User Load (0.3ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
  6. sql (0.1ms) BEGIN
  7. AREL (0.3ms) UPDATE `users` SET `visit_count` = 11,`perishable_token` = 'YG3s4yB01FxUMdMcK8m',`updated_at` = '2011-05-24 15:44:08' WHERE `users`.`id` = 1
  8. sql (0.3ms) COMMIT
  9. Option Load (0.3ms) SELECT `options`.* FROM `options` WHERE (`options`.user_id = 1) LIMIT 1
  10. Category Load (0.2ms) SELECT `categories`.* FROM `categories` WHERE `categories`.`id` = 2 LIMIT 1
  11. sql (0.1ms) BEGIN
  12. 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
  13. AREL (0.3ms) UPDATE `categories` SET `name` = 'Lunchr5',`updated_at` = '2011-05-24 15:44:09' WHERE `categories`.`id` = 2
  14. sql (0.3ms) COMMIT
  15. Redirected to http://localhost:3000/categories
  16. Completed 302 Found in 179ms

我是否必须破解骨干以将:id添加到网址或我错过了什么?

解决方法

Backbone将根据Model.url()的结果确定要使用的url.所以,如果你有
  1. class Category extends Backbone.Model
  2. name: 'category'
  3. url: ->
  4. host + '/categories'

url骨干网的保存方法将在服务器上尝试:host’/ categories’

如果你没有定义url函数,url函数的默认行为将委托给它所在的集合.所以如果你有一个集合

  1. class Categories extends Backbone.Collection
  2. model:Category
  3. url: ->
  4. host + '/categories'
  5. class Category extends Backbone.Model
  6. name: 'category'

属于Categories集合的Category实例将自动使用url host’/ categories”/’category.id保存到服务器.

现在,如果您的模型不是集合的一部分,那么您不能这样做.您必须覆盖模型中的url函数,如下所示

  1. class Category extends Backbone.Model
  2. name: 'category'
  3. url: ->
  4. u = "#{host}/categories/"
  5. u = "#{u}#{this.id}" if this.id
  6. u

请注意,这不是黑客行为.这是正确使用骨干.实际上在未来的骨干版本中,我相信url函数没有默认行为,并且必须为所有模型编写url函数.

猜你在找的Ruby相关文章