Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested routing in Ruby on Rails

My model class is:

class Category < ActiveRecord::Base
  acts_as_nested_set
  has_many :children, :foreign_key => "parent_id", :class_name => 'Category'
  belongs_to :parent, :foreign_key => "parent_id", :class_name => 'Category' 


  def to_param
    slug
  end
end

Is it possible to have such recursive route like this: /root_category_slug/child_category_slug/child_of_a_child_category_slug ... and so one

Thank you for any help :)

like image 252
vooD Avatar asked Apr 01 '10 08:04

vooD


2 Answers

You can do that with regular routes and Route Globbing, so for example,

map.connect 'categories/*slugs', :controller => 'categories', :action => 'show_deeply_nested_category'

Then in your controller

def show_deeply_nested_category
  do_something = params[:slugs]  # contains an array of the path segments
end

However, note that nested resource routing more than one level deep isn't recommended.

like image 81
Corey Avatar answered Oct 22 '22 18:10

Corey


I doubt it, and it's not a good idea. Rails Route mapping code is complex enough without having to dynamically try to encode & decode (possibly) infinite route strings.

like image 2
simianarmy Avatar answered Oct 22 '22 19:10

simianarmy