我已经像这样设置了我的版本化 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
删除声音
<%= button_to 'Delete', @sound, :confirm => 'Are you sure?', :method => :delete %>
它以以下形式生成以下网址action
:
"/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:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script> <!-- must be >= 1.4.4 for the rails 3 link js to work—>
<script src="/javascripts/jquery-ujs/src/rails.js?1304736923" type="text/javascript"></script>
我知道这是tl;dr
但我的问题是:“我需要在我的 button_to link_to 和其他视图标签中添加什么才能使 url 帮助程序为我的设置生成正确的路径? ”我已经尝试了几乎所有我能想到的组合,但是永远无法让他们最终出现在正确的地方。