Nested Routing in Ruby on Rails

My model class:

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 that such a recursive route would be: /root_category_slug/child_category_slug/child_of_a_child_category_slug ... and therefore one

Thanks for any help :)

+7
ruby ruby-on-rails nested-sets routing
source share
4 answers

You can do this using regular routes and Route Globbing , 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 is not recommended for more than one depth level.

+4
source share

I doubt it, and this is not a good idea. Rails route encoding is quite complex, without the need to dynamically try to encode and decode (possibly) endless route lines.

+2
source share

You can use restrictions in rails routing. eg:

 match '*id', :to => 'categories#show', :constraints => TaxonConstraint.new class TaxonConstraint def matches?(request) path = request.path.slice(1..(request.path.length-1) path = path.split('/') return false if path.length != path.uniq.length return true if Category.check(path.last).first false end end 
Class

splits your path into "/" and checks db for the last element in db. if not found, skips the route. if anyone knows how to solve it better, it would be nice to hear.

+1
source share

This is not easy (read: I do not know how to do this), and it is not recommended. Imagine if you have 10 categories, you don’t want the URL to be /categorya/categoryb/categoryc/categoryd/categorye/categoryf/categoryg/categoryh/categoryi/categoryj .

Perhaps a maximum level of 3 will provide you with the strength you desire without polluting the URL?

0
source share

All Articles