Rails 3使用可选范围下的资源进行路由

我已经设置了这样的版本化API ,只需稍微调整即可实现向后兼容。 在我的路线中,我有:

scope '(api(/:version))', :module => :api, :version => /v\d+?/ do … scope '(categories/:category_id)', :category_id => /\d+/ do … resources :sounds … end end 

已达到成功的目标,让以下url到达同一个地方

 /api/v1/categories/1/sounds/2 /api/categories/1/sounds/2 /categories/1/sounds/2 /sounds/2 

我的目录结构是这样的:

在此处输入图像描述

我看到的问题在于我的观点中的链接世代。 例如,在声音节目页面上,我有一个button_to来删除声音

  'Are you sure?', :method => :delete %> 

这会在表单action生成以下URL:

 "/api/sounds/1371?version=1371" 

此外, delete方法不起作用,而是作为POST发送

rake routes的有趣部分是:

  sounds GET (/api(/:version))(/categories/:category_id)/sounds(.:format) {:controller=>"api/sounds", :version=>/v\d+?/, :action=>"index", :category_id=>/\d+/} POST (/api(/:version))(/categories/:category_id)/sounds(.:format) {:controller=>"api/sounds", :version=>/v\d+?/, :action=>"create", :category_id=>/\d+/} new_sound GET (/api(/:version))(/categories/:category_id)/sounds/new(.:format) {:controller=>"api/sounds", :version=>/v\d+?/, :action=>"new", :category_id=>/\d+/} edit_sound GET (/api(/:version))(/categories/:category_id)/sounds/:id/edit(.:format) {:controller=>"api/sounds", :version=>/v\d+?/, :action=>"edit", :category_id=>/\d+/} sound GET (/api(/:version))(/categories/:category_id)/sounds/:id(.:format) {:controller=>"api/sounds", :version=>/v\d+?/, :action=>"show", :category_id=>/\d+/} PUT (/api(/:version))(/categories/:category_id)/sounds/:id(.:format) {:controller=>"api/sounds", :version=>/v\d+?/, :action=>"update", :category_id=>/\d+/} DELETE (/api(/:version))(/categories/:category_id)/sounds/:id(.:format) {:controller=>"api/sounds", :version=>/v\d+?/, :action=>"destroy", :category_id=>/\d+/} 

和服务器日志显示:

 Started POST "/api/sounds/1371?version=1371" for 127.0.0.1 at Fri May 06 23:28:27 -0400 2011 Processing by Api::SoundsController#show as HTML Parameters: {"authenticity_token"=>"W+QlCKjONG5i/buIgLqsrm3IHi5gdQVzFGYGREpmWYs=", "id"=>"1371", "version"=>371} 

我使用JQuery作为我的UJS,并为JQuery提供了最新版本的rails.js:

  

原来解决方案很简单。 我在这里犯了两个错误,导致生成错误的路径和附加params的url。

  1. resources :sounds之上resources :sounds路线,我错误地有这条线:

     match '/sounds/:id(/:format)' => 'sounds#show' 

    我有这一行,以便可以页面缓存sounds/123/xml 。 这导致show所有路由,我意识到错误是我在parens中有:format ,匹配应该是get 。 现在它写道:

     get '/sounds/:id/:format' => 'sounds#show' 
  2. 接下来,在button_to链接中,我将@sound对象放置为我的第二个参数。 Rails试图通过推断这个正确的URL来实现智能,但是使用可选的api :version param失败了。 将其更改为

     sound_path(:id => @sound.id) 

    像魅力一样工作。