Rails 3 routing, how to combine multiple?

How do I map multiple controllers like an ID?

I tried this on my routes:

match '/:id' => 'kategoris#show'
match '/:id' => 'tags#show'



source to share

3 answers

Rails controller routing is not right for you if you want to match http://example.com/<something>


You can create one ThingsController:

match '/:id' => 'things#show'


and then do something appropriate in your ThingsController.

Eg. in Sinatra (which you could install as a Rack middleware), you would do this:

get "/:id" do :id
  if(@tag = Tag.find(:id))
     haml :tag
  elsif(@category = Category.find(:id))
     haml :category
     pass #crucially passes on saying 'not found anything'.


Either way, you'll get a cry of anguish from the RESTful Rails enchevners.



If you can implement an identifiable difference in tag id and category id, then you can use constraints to find them. For example, if categories always start with a number and tags never do, you can do this.

match '/:id' => 'categories#show', :constraints => { :id => /^\d+/ }
match '/:id' => 'tags#show'


The first line will only match if it :id

starts with a digit. If it doesn't match, the second line catches the leftovers. So; /67-something

sent to the category controller, and /something

sent to the tag controller.



match 'kategoris/:id' => 'kategoris#show'
match 'tags/:id' => 'tags#show'



match '/:id/kategoris' => 'kategoris#show'
match '/:id/tags' => 'tags#show'




All Articles