1

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.

Community
  • 1
  • 1
Tricnic
  • 115
  • 1
  • 6
  • Why do you put brackets around the globbing for categories? – hahcho Feb 03 '15 at 10:26
  • Y'know... I'm not sure. I could have sworn it was needed, but looking over the documentation, I guess it isn't. It seems to work the same with and without the (). – Tricnic Feb 03 '15 at 21:11
  • Spending some more time on it, I realize I could use `www.example.com/cat1/cat2/.../catn/posts/post1`, but I'd like to avoid that if possible. I've seen it done in blogging engines, I'm just not sure how to go about it. – Tricnic Feb 03 '15 at 21:26
  • Is the post1 going to be alphanumeric? If it is going to be numeric you could put a route constraint that uses a regex. – Blankman May 31 '15 at 00:31

0 Answers0