Need a Rails route with a possible period in the :id, but also retain the optional :format

放肆的年华 提交于 2019-12-03 04:55:48

问题


I have a Rails route that takes stock ticker symbols as the :id

  • feeds/AMZN will return a page for Amazon
  • feeds/AMZN.csv will return a CSV representation of the same data.

But I also need to accomodate stocks like VIA.B (Viacom) so that both of these routes work:

feeds/VIA.B (html)
feeds/VIA.B.csv (csv)

Is this possible? How would I set the routing up?


回答1:


I ran into this while patching the RubyGems API recently (trying to access the flickr.rb using the API (/api/v1/gems/flickr.rb.json) was not working).

The trick was to supply the route with a regexp to handle the :id parameter, and then specify valid :format. Keep in mind that the :id regexp needs to be "lazy" (must end with a question mark), otherwise it will eat the .csv and assume that it's part of the id. The following example would allow JSON, CSV, XML, and YAML formats for an id with a period in it:

resources :feeds, :id => /[A-Za-z0-9\.]+?/, :format => /json|csv|xml|yaml/



回答2:


Old question, but I found a much simpler way that works with nested routes (I'm on Rails 3.2.4). This way allows all characters (including the dot) as opposed to the accepted answer which makes you specify the allowed charcters.

resources :feeds, :id => /([^\/])+?/

Note that I had found some other suggestions (e.g. here: http://coding-journal.com/rails-3-routing-parameters-with-dots/) of doing something like:

resources :feeds, :id => /.*/

but that didn't work for me with nested routes for some reason.




回答3:


I ran into this as well, but in the reverse direction. (url_for() produces "No route matches" only for IDs with . in them.)

I'm using match instead of resources to allow some name munging. If you're doing the same, this is what the fix looks like:

match "feeds/:id" => "stocks#feed", :constraints => {:id => /[\w.]+?/, :format => /html|csv/}


来源:https://stackoverflow.com/questions/6719797/need-a-rails-route-with-a-possible-period-in-the-id-but-also-retain-the-option

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!