HXH
HXH

Reputation: 1663

About Rails routes

My Rails4 app has some routes

get '/mem(/:id)(/:action)(.format)' ,:controller=>'sns_mem',id: /\d+/
get '/group(/:id)(/:action)(.format)' ,:controller=>'sns_group',id: /\d+/
get '/article(/:id)(/:action)(.format)' ,:controller=>'sns_article',id: /\d+/
get '/photo(/:id)(/:action)(.format)' ,:controller=>'sns_photo',id: /\d+/

As you can see,these routes are similar,so I want to know how to merge these routes to one?

Upvotes: 0

Views: 54

Answers (1)

iMacTia
iMacTia

Reputation: 671

['mem', 'group', 'article', 'photo'].each do |r|
    get "/#{r}(/:id)(/:action)(.format)" ,:controller=>"sns_#{r}",id: /\d+/
end

Never tried with loops in routes.rb file, but should work. It is not properly ONE route, it will create one route for each element of the array, but at least you will avoid typos. Moreover, regexp are generally slower.

Upvotes: 1

Related Questions