Friday, 15 April 2011

ruby - rails - how to make nested route with ancestry -



ruby - rails - how to make nested route with ancestry -

i have single model:

class page < activerecord::base has_ancestry validates :slug, :name, uniqueness: true, presence: true before_validation :generate_slug def to_param slug end def generate_slug self.slug = russian.translit(name).parameterize end end

and i'm using ancestry gem create tree of pages , subpages, i.e. page can have multiple sub-pages , sub-pages can have multiple sub-pages, , on infinity.

but problem can't create /page-1/page-1-2/page-1-2-1. sub-pages have url is: /page-1-2 or /page-1-3-1.

my routes.rb:

rails.application.routes.draw '/pages' => 'pages#index' resources :pages, path: "", path_names: { new: 'add' } root 'pages#index' end

how create nested url?

thanks!

as far know there's no neat way of capturing nested tree structured routes dynamic permalinks, can create named route capture pretty nested pages path:

get '/p/*id', :to => 'pages#show', :as => :nested_pages

also, create sure update slug of page object have nested urls, i.e.: append parent pages' slug it. example:

page1.slug = '/page-1' page2.slug = '/page-1/page-2' # page2 kid of page1 page3.slug = '/page-1/page-2/page-3' # page3 kid of page2

so, create work, can alter generate_slug method in page model class:

def generate_slug name_as_slug = russian.translit(name).parameterize if parent.present? self.slug = [parent.slug, (slug.blank? ? name_as_slug : slug.split('/').last)].join('/') else self.slug = name_as_slug if slug.blank? end end

ruby-on-rails ruby nested-routes ancestry

No comments:

Post a Comment