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.fin开发者_C百科d_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
You can nest your match
statement in your parent resource like this (in Rails 3 at least):
resources :things do
match "categories/:category_id" => 'categories#show', :as => :category
end
This should create a route like /things/:thing_id/categories/:category_id
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
精彩评论