2014-08-27 44 views
1

我試圖讓我的路線是這樣工作的:Rails的友好ID定義路由

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

我使用:

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

我有了很多文章

類別

現在的url結構是:

/categories/

/用品/

,因爲我的routes.rb文件看起來像這樣:

resources :categories 
resources :articles 

我article.rb文件:

class Article < ActiveRecord::Base 
    belongs_to :category 

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

    def slug_candidates 
     [ 
     :name 
     ] 
    end 
end 

這裏是我的類別。 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 

如果我做這樣一個嵌套的路線:

resources :categories do 
    resources :articles 
end 

則結構變得/categories/<category slug>/articles/<article slug>

回答

0

這正是我想要的。它擴展了mbillard的答案:

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] 
2

你可以這樣做:

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

甚至:

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

但要小心,因爲這會在/categories/:category_slug/.../之後收到任何東西。不過,我不知道像newedit這樣的常規路線有什麼問題。