Martin
Martin

Reputation: 11336

Refactoring Rails 3 Routes

I have this in my routes:

get '/boutique/new' => 'stores#new', :as => :new_store, :constraints => { :id => /[a-z0-9_-]/ } 
post '/boutique' => 'stores#create', :as => :create_store, :constraints => { :id => /[a-z0-9_-]/ }
get '/:shortname' => 'stores#show', :as => :store, :constraints => { :id => /[a-z0-9_-]/ }
get '/:shortname/edit' => 'stores#edit', :as => :edit_store, :constraints => { :id => /[a-z0-9_-]/ }
put '/:shortname' => 'stores#update', :as => :update_store, :constraints => { :id => /[a-z0-9_-]/ }
delete '/:shortname' => 'stores#delete', :as => :destroy_store, :constraints => { :id => /[a-z0-9_-]/ }

Is there a cleaner way to do the same? It doesn't look any elegant and even less if I add some more controls/actions to it.

Thank you.

Upvotes: 0

Views: 171

Answers (1)

PreciousBodilyFluids
PreciousBodilyFluids

Reputation: 12001

Your best option would be to stick to the standard resource routes. If anyone else ever needs to work on the application you're building, they'll thank you.

That said, if you really need this routing setup (for whatever reason), try the following:

controller :stores do
  constraints :id => /[a-z0-9_-]/ do
    get    '/boutique/new'    => :new,    :as => :new_store
    post   '/boutique'        => :create, :as => :create_store
    get    '/:shortname'      => :show,   :as => :store
    get    '/:shortname/edit' => :edit,   :as => :edit_store
    put    '/:shortname'      => :update, :as => :update_store
    delete '/:shortname'      => :delete, :as => :destroy_store
  end
end

I haven't actually tested it, but that should work fine.

Upvotes: 2

Related Questions