开发者

Shorter URLs for resourceful routes

开发者 https://www.devze.com 2023-03-18 20:47 出处:网络
I thought this would be trivial, but can\'t find it anywhere. My site has a lot of different models, that are all interconnected.

I thought this would be trivial, but can't find it anywhere.

My site has a lot of different models, that are all interconnected. Let's say:

  • Author
  • Book
  • Photo

A book and a photo both have an author, and a photo can be inside a book.

resources :authors do
  resources :books

etc..

So, using nested resourceful routes, we get stuff like:

/authors/john-smith/photos/picture-of-a-house

or

/books/house-renovation/photos/picture-of-a-house

These URLs match with the breadcrumbs I have on my site. A breadcrumb would look like this:

Home > Books > House Renovation > Photos > Picture of a House

The problem is that these URLs and breadcrumbs become too long, and too "resource-like". I mean, you can spot a Rails website from far away if it uses the /categories/category_id/products/id format.

Is there a way to shorten this, maybe even making it beautiful? It still needs both the Category and the开发者_StackOverflow中文版 Product names, but a maximum of one parameter before that. Something like:

Book_Photos > House Renovation > Picture of a House


You might be able to do this by simply passing in the :path option to your resources and setting it to an empty string, in your route file.

I've just played around with the following:

  resources :authors, :path => "" do
    resources :books, :path => ""
  end

Running rake routes on the command line it produced this:

          author_books    GET    /:author_id(.:format)           books#index
                          POST   /:author_id(.:format)           books#create
          new_author_book GET    /:author_id/new(.:format)       books#new
         edit_author_book GET    /:author_id/:id/edit(.:format)  books#edit
              author_book GET    /:author_id/:id(.:format)       books#show
                          PUT    /:author_id/:id(.:format)       books#update
                          DELETE /:author_id/:id(.:format)       books#destroy
                  authors GET    /                               authors#index
                          POST   /                               authors#create
               new_author GET    /new(.:format)                  authors#new
              edit_author GET    /:id/edit(.:format)             authors#edit
                   author GET    /:id(.:format)                  authors#show
                          PUT    /:id(.:format)                  authors#update
                          DELETE /:id(.:format)                  authors#destroy

The Rails Routing Guide is pretty thorough when it comes to explaining what can be done.

0

精彩评论

暂无评论...
验证码 换一张
取 消