craig
craig

Reputation: 26262

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

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)?

Upvotes: 0

Views: 1295

Answers (2)

Vojto
Vojto

Reputation: 6959

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('+').

Upvotes: 0

Jonathan Julian
Jonathan Julian

Reputation: 12264

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.

Upvotes: 1

Related Questions