2014-08-27 64 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这样的常规路线有什么问题。