Search code examples
ruby-on-railsroutestreeslug

Rails slug for ancestry model


I have ancestry for my category model. Im using slug gem. Currently i have following:

class Category < ActiveRecord::Base
  slug :name
end


class CategoriesController < ApplicationController
  inherit_resources
  defaults :finder => :find_by_slug
  def show
    @category = Category.find_by_slug(params['category_id'])
    show!
  end
end

  match "categories/:category_id" => 'categories#show', :as => :category

This works fine, but i want to show parent/children path instead of /children

if my category have parent. How to reach this?

For example i have BMW category and x5 as subcategory. I have now this links: /categories/bmw for bmw and /categories/x5 for x5. i need this link categories/bmw/x5 instead of subcategory


Solution

  • match "categories/:category_id" => 'categories#show', :as => :category_short
    match "categories/:category/:category_id" => 'categories#show', :as => :category_long
    
      def category_path(category)
        unless category.is_root?
          category_long_path category.parent, category
        else
          category_short_path category
        end
      end