Rails nested routing for dynamic pages

In my Rails application, I have pages that are stored in a database.

So for example:

id: 1
name: 'About'
slug: 'about'
parent_id: null

id: 2
name: 'Team'
slug: 'team'
parent_id: 1

id: 3
name: 'Cameron'
slug: 'cameron'
parent_id: 2

Slug is used to access them through routing as follows:

match '/:slug' => 'pages#show', :via => :get, :as => :page

Therefore, I could access these pages at:

/about
/team
/cameron

What I want to do is use parent_idso that routing becomes the following:

/about/team/cameron

Can this be done using only routing? Or do I need to do something else?

+4
source share
2 answers

Get help from Friendly gem , it makes bullet routing easier.

Alternative options for defining routes, for example

, , :

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

, , slug , URL-, : . :

 page1.slug = '/about'
 page2.slug = '/about/team' # team is a child of about
 page3.slug = '/about/team/cameron' # cameron is a child of team

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

, , , , generate_slug :

 def generate_slug
   name_as_slug = 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
0

, . , , , , , :

  • , get '*path', to: 'pages#show', , .
  • params['path'] pages#show.

. , . slug, , slug ..

, , , . -, - , , PostgreSQL ltree.

+1

Source: https://habr.com/ru/post/1660269/


All Articles