Reputation: 1287
Right now there are two models: Category and Product. Categories are self joining to make sub_categories. Category has_many Product, who of course belongs_to Category.
The question I have is this: How Do I map the routes for these resources so that they have SEO friendly URLS.
For example: If the user clicks on the "Lamas" category, then clicks on the "Maintenence" sub-category, and then finally clicks on the "Lama Polish" Product. The path will be: http://lamasareawesome.com/categories/1/categories/26/products/11
What I want is: http://lamasareawesome.com/lamas/maintenence/lama-polish
So far Im not having much luck trimming the controller name out of the path, and replacing it with a model attribute.
Upvotes: 0
Views: 91
Reputation: 101871
Creating routes which use another attribute than the ID is pretty trivial. FriendlyID a great out of box solution but it does will only get you to URLs that look like:
/categories/lamas/categories/maintenance/products/lama-polish
Creating URL's such as lamas/maintenence/lama-polish
is definitely possible but will be difficult since its not conventional and there are many potential pitfalls.
You could for example start out with:
resources :categories, path: '/' do
resources :categories, path: '' do
# resources :products
end
end
Which will create:
Prefix Verb URI Pattern Controller#Action
category_categories GET /:category_id(.:format) categories#index
POST /:category_id(.:format) categories#create
new_category_category GET /:category_id/new(.:format) categories#new
edit_category_category GET /:category_id/:id/edit(.:format) categories#edit
category_category GET /:category_id/:id(.:format) categories#show
PATCH /:category_id/:id(.:format) categories#update
PUT /:category_id/:id(.:format) categories#update
DELETE /:category_id/:id(.:format) categories#destroy
categories GET / categories#index
POST / categories#create
new_category GET /new(.:format) categories#new
edit_category GET /:id/edit(.:format) categories#edit
category GET /:id(.:format) categories#show
PATCH /:id(.:format) categories#update
PUT /:id(.:format) categories#update
DELETE /:id(.:format) categories#destroy
But then there is a supersized gotcha - let's say the request is for
GET /lamas/joe-the-lama
How is Rails supposed to know that this request should be handled by LamasController
and not CategoriesController
? You would have to do a database query for both. Of course this is not an issue if you always have two categories but you get my drift - things are going to get complicated fast.
The standard Rails style restful routing may be a bit wordy but it does avoid a lot of potential ambiguities.
Upvotes: 1