Nested RoR Categories

people! I wonder how to make url like: site.com/coding/ruby/rails/article-name As you can see, there is a nested category. I already looked at actions like a tree and amazing nested sets, but it does URLs like site.com/rails/article-name.

So please help me

+3
source share
3 answers

If you want to use a resource controller, complete the route as follows:

scope '(*categories)' do
  resources :articles
end

for this you will need to use the "article" at the end of your URLs: / coding / ruby ​​/ rails / articles / article-name

or you can use a route like this:

match '(*categories)/:id' => 'articles#show', :as => :article

this will allow you to do article_path (: categories => 'coding / ruby ​​/ rails' ,: id => article.friendly_id)

//ruby ​​/rails/article-name

awesome_nested_set, , -

article.category.self_and_ancestors.join("/")
+4
0

To configure this, you start with a route that performs “routing”:

match "*category" => "categories#show"

or

match "categories/*category" => "categories#show"

in your controller, you will get all parts of the url through a hash params. To keep clean, define the search logic in your model

def show
  @category = Category.find_recursive(*params[:categories])
end

in your model, define a category search method. I assume act_as_tree is defined in your model

def self.find_recursive(*categories)
  children = roots
  last = nil
  categories.each do |category|
    return unless children

    last = children.find_by_permalink(category)
    children = last.children
  end
  last
end
0
source

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


All Articles