Last Updated: February 25, 2016
·
648
· kelion

Rewrite default collection/member routes

Sometimes you should rewrite default collection or member routes in rails to add or replace default params. For example, you have "channels" controller, and you want have path's like "channelspath", "channelpath". In index action you want to have "flag" option for filter collection, like: channels/active, but default index url looks like "/channels". And for member you want url like category/name. For rewrite collection url you can just use :as => (empty string):

resources :channels do
  get '(/:flag)', :defaults => {:flag => 'all'}, :as => '', :on => :collection
end

More difficult to rewrite member url, because if you write

resources :channels do
  get ':category/:slug', :as => '', :on => :member
end 

you have url like :id/:category/:slug. For apply new format of url, you should use "resource" instead "resources":

resource :channel, :path => ':category/:slug'

Now you have correct channels_path and channel_path.

Why not use match? Because if you want to use nested controllers, you shoud write "match" for all of nested controller actions.