I am working on a very simple blogging engine, no bells or whistles needed, and I've come to the problem of build routes for the arbitrary number of subcategories.
I want to have a post view that displays all posts in the category (posts#index) and a view that displays a specific post (posts#show).
I have the following models
class Category < ActiveRecord::Base
belongs_to :parent, foreign_key: 'parent_id', class_name: 'Category'
has_many :children, foreign_key: 'parent_id', class_name: 'Category'
has_many :posts
end
class Post < ActiveRecord::Base
belongs_to :category
end
As you can see, the category can have a category as a parent. I'd like to be able to do something along the lines of:
example.com/category1/category2/.../categoryn
rendering posts#index
and
example.com/category1/category2/.../categoryn/post1
rendering posts#show
I've been trying to use globbing, a la:
get '(*categories)' => 'posts#index', as: :posts
get '(*categories)/:id' => 'posts#show', as: :post
but the posts_path keeps globbing up the :id that should be handled by the post_path. If I reverse the routes, then categoryn is treated as the post :id, rather than the bottom category in the tree.
Ruby on Rails: Routing for a tree hierarchy of places is the closest I could find, addressing the use of globbing, but it doesn't deal with the :id problem.
Any help, or even a "You can't do that for these reasons", would be appreciated. If you could point me to a gem that handles this nicely that I could reverse engineer from, that would be awesome.