【问题标题】:How to create this route?如何创建这条路线?
【发布时间】:2016-01-29 09:00:13
【问题描述】:

我有以下路线:

resources :articles, except: [:index] do
   collection do
      get 'author/:id/articles' => 'articles#index', as: 'index_articles'
   end
end

这会导致:

GET    /api/v1/articles/:id/author/:id/articles(.:format)

我怎样才能把它变成以下?:

GET    /api/v1/author/:id/articles(.:format)  

【问题讨论】:

  • 如果你在resources :articles之外写这个get 'author/:id/articles' => 'articles#index', as: 'index_articles'你会得到想要的路线。
  • 是的,非常感谢,您会添加这个作为答案吗?

标签: ruby-on-rails ruby ruby-on-rails-4 routes


【解决方案1】:
# config/routes.rb
resources :articles, except: [:index]
resources :authors, path: "author", only: [] do
   resources :articles, only: :index, on: :member #-> url.com/author/:id/articles
end

【讨论】:

  • 谢谢,使用member 代替其他解决方案有什么好处。或者这只是惯例?
  • 约定俗成,也是extensible。比使用单独的路线更好地确定资源范围,以防您希望之后添加额外的路线
【解决方案2】:

写这个

get 'author/:id/articles' => 'articles#index', as: 'index_articles'

resources :articles 块之外。

【讨论】:

    猜你喜欢
    • 2017-03-21
    • 2019-11-22
    • 2015-09-13
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    相关资源
    最近更新 更多