ruby-on-railsruby-on-rails-4routescustom-routes

Rails Routing: Flexible Resource Path depending on attributes


How could you make a route for resource be flexible enough depending on its attributes?

For example,

resources :articles, param: :article_slug do
    member do
      resources :comments
    end
end

Article has attributes of title, category, slug, etc

But the client wants it that the category must be the first present in url, such as: /entertainment/articles/:article_slug/comments/:id or /sports/articles/:article_slug/comments/:id. I don't know what is the right approach for this one.


Solution

  • Try

    scope path: ':category' do
      resources :articles, param: :article_slug do
          resources :comments
          end
      end
    end
    

    And generate the url in this way,

    article_comment_path(@article, @comment, category: @article.category)