Rails 3 routing how to match multiple?

大憨熊 提交于 2019-12-24 09:28:05

问题


How do I match multiple controller for example an id?

I have tried this in my routes:

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

回答1:


Rails controller routing isn't appropriate for you if you're wanting to match http://example.com/<something>.

You could create a single ThingsController:

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

and then do something appropriate in your ThingsController.

Eg. in Sinatra (which you could mount as a Rack middleware) you'd 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

You're going to get a scream of anguish from the RESTful Rails envangelists either way.




回答2:


If you can implement an identifiable difference in your tag id's and category id's, then you can use constraints to look them up. For example if categories always begin with a number and tags never do then you can do this.

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

The first line would match only if :id begins with a digit. If that doesn't match, the second line catches the leftovers. So; /67-something gets routed to categories controller and /something gets routed to the tags controller.




回答3:


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

or

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


来源:https://stackoverflow.com/questions/5786725/rails-3-routing-how-to-match-multiple

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