How to embed multiple tags in Rails routes, like Stack Overflow

荒凉一梦 提交于 2019-12-10 00:32:19

问题


When one selects a tag on Stack Overflow, it is added to the end of the URL. Add a second tag and it is added to the end of the URL after the first Tag, with a + delimiter. For example:

http://stackoverflow.com/questions/tagged/ruby-on-rails+best-practices

How is this implemented? Is this a routing enhancement or some logic contained in the TagsController? Finally, how does one 'extract' these tags for filtering (assuming that they are not in the params[] array)?


回答1:


Vojto's answer is correct, but note that you can also use Route Globbing on the server side to handle this cleanly. A route defined as /:controller/*tags will match /questions/ruby/rails/routing, and in the questions_controller, params[:tags] will be an array containing ['ruby','rails','routing']. See the Routing docs.




回答2:


I think Rails doesn't mind if params contains symbols like +. That means, you can access all tags as one argument, create a route like: '/show/:tags'

Then you can access params[:tags], which will be string like 'ruby+rails'. You can simply do 'ruby+rails'.split('+') to turn it into an array.

By that you can easily append new tag to this array, and turn it back into string with my_array_with_tags.join('+').



来源:https://stackoverflow.com/questions/2539819/how-to-embed-multiple-tags-in-rails-routes-like-stack-overflow

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