1

I'm trying to get my routes to work like this:

/articles/<category slug>/<article slug>

I'm using:

ruby '2.1.2'
gem 'rails', '4.1.4'
gem "friendly_id", "~> 5.0.1"

I have a category that has many articles

the url structure now is:

/categories/

/articles/

because my routes.rb file looks like this:

resources :categories
resources :articles

my article.rb file:

class Article < ActiveRecord::Base
    belongs_to :category

    extend FriendlyId 
    friendly_id :slug_candidates, use: [:slugged, :globalize]

    def slug_candidates
      [
        :name
      ]
    end
end

here's my category.rb:

class Category < ActiveRecord::Base
        has_many :articles

        extend FriendlyId 
        friendly_id :slug_candidates, use: [:slugged, :globalize]

        # Try building a slug based on the following fields in
        # increasing order of specificity.
        def slug_candidates
          [
            :name
          ]
        end
end

If I do a nested route like this:

resources :categories do
   resources :articles
end

then the structure becomes /categories/<category slug>/articles/<article slug>

infused
  • 24,000
  • 13
  • 68
  • 78
Pavan Katepalli
  • 2,372
  • 4
  • 29
  • 52

2 Answers2

2

You could do something like:

resources :categories do
  get ':article_slug', to: 'articles#show' # => /categories/:category_id/:article_slug
end

or even:

resources :categories do
  resources :articles, path: ''
end

Be careful though, because this will catch anything after /categories/:category_slug/.../. I don't know what's the behavior with the regular routes like new and edit though.

mbillard
  • 38,386
  • 18
  • 74
  • 98
1

this does exactly what I want. It's expanded off of mbillard's answer:

  get "/articles", to: "articles#index"
  resources :categories, path: 'articles' do
    resources :articles, path: '', only: [:show]
  end
  resources :articles, only: [:index, :new, :edit, :create, :update, :destroy]
Pavan Katepalli
  • 2,372
  • 4
  • 29
  • 52