Ruby on Rails 3: Change default controller and parameter order in routing
I have a Rails app that has a controller called domain
which has a nested controller called subdomain
and stats
. I have defined them in routes.rb
:
resources :domains do
resources :subdomains, :stats
end
I have changed the to_param of the domain and subdomain models to use the name of the do开发者_运维问答main, e.g.: the routing I get is http://site/domains/foo/subdomains/bar
.
I would like to tidy it up to so that instead of using http://site/domains/foo/subdomains/bar
I could access it with just http://site/foo/subdomains/bar
. I have tried the following in routes.rb
:
match "/:id/" => "domains#show", :as => :domain
Which works fine, but it only gives me the ability to use the path http://site/foo
but for example http://site/foo/subdomains/bar
doesn't. I could create match lines for every respective model and nested model but that does nothing to other helpers besides domain_url
- i.e. edit_domain_url points to /domains/foo/edit/
instead of /foo/edit
.
Is there a way to change the routing so that the resources
generates helpers that point to the root url without the 'domains' part?
The single match
in your routes creates only one route. Resource helpers create many routes at once. Luckily there are a lot of options for customisation. If you want to omit /domains/
from your paths, it's as simple as:
resources :domains, :path => "/" do
resources :subdomains, :stats
end
With the above in config/routes.rb
, running rake routes
says the following:
domain_subdomains GET /:domain_id/subdomains(.:format)
domain_subdomains POST /:domain_id/subdomains(.:format)
new_domain_subdomain GET /:domain_id/subdomains/new(.:format)
edit_domain_subdomain GET /:domain_id/subdomains/:id/edit(.:format)
domain_subdomain GET /:domain_id/subdomains/:id(.:format)
domain_subdomain PUT /:domain_id/subdomains/:id(.:format)
domain_subdomain DELETE /:domain_id/subdomains/:id(.:format)
domain_stats GET /:domain_id/stats(.:format)
domain_stats POST /:domain_id/stats(.:format)
new_domain_stat GET /:domain_id/stats/new(.:format)
edit_domain_stat GET /:domain_id/stats/:id/edit(.:format)
domain_stat GET /:domain_id/stats/:id(.:format)
domain_stat PUT /:domain_id/stats/:id(.:format)
domain_stat DELETE /:domain_id/stats/:id(.:format)
domains GET /(.:format)
domains POST /(.:format)
new_domain GET /new(.:format)
edit_domain GET /:id/edit(.:format)
domain GET /:id(.:format)
domain PUT /:id(.:format)
domain DELETE /:id(.:format)
Looks like all the routes you need!
精彩评论