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'

      

+1
ruby ruby-on-rails friendly-url ruby-on-rails-3


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
  else
     pass #crucially passes on saying 'not found anything'.
  end
end

      

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

+4


source to share


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.

+1


source to share


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

      

or

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

      

0


source to share







All Articles
Loading...
X
Show
Funny
Dev
Pics