如何在 rails 路由中正确使用 :path_names?

How correctly use :path_names in rails routes?

我正在编写 rails 应用程序,我需要更改应用程序的一些 URL 路径。但我不想破坏我的测试并更改视图、js 或控制器...

这是我的路线:

  resources :posts, path: 'news' do
    member do
      get  'edit/page/:page', as: :edit,    action: :edit
      post '/approve',        as: :approve, action: :approve
      post '/reject',         as: :reject,  action: :reject
    end

    collection do
      get :my
      get :shared_with_me
      get :filtered
    end
  end

如您所见,我找到了一种将所有网站路径中的 domain.com/posts 更改为 domain.com/news 的方法。

现在我需要更改路径列表:

我正在尝试使用 :path_names 更改此路径,但它不起作用...

这是更新的路线:

  resources :posts, path: 'news', path_names: {index: 'all', show: 'preview', new: 'request'} do
    member do
      get  'edit/page/:page', as: :edit,    action: :edit
      post '/approve',        as: :approve, action: :approve
      post '/reject',         as: :reject,  action: :reject
    end

    collection do
      get :my
      get :shared_with_me
      get :filtered
    end
  end

当我进行此更改并运行 rake routes - 仅出现 GET news/request..

但为什么我没有看到 GET news/allGET news/:id/review

请帮我解决一下。 谢谢!

您可以指定用于资源的控制器,而不是使用 path hack:

resources :news, controller: 'posts' do

end

当涉及到其他人的问题时,也许您应该了解 RESTful 默认设置的方式和原因。

使用 /news/all 非常特殊 - 在 REST 中它暗示如果路径描述资源而不是 "root" 应该显示所有项目。

get 'edit/page/:page'

简直太奇怪了。如果页面是 news 的嵌套资源,您可以这样声明它:

resources :news, controller: 'posts' do
   resources :pages
   # or
   resource :page
end

您也不应该使用 POST 动词来批准/拒绝故事。 POST 表示您正在创建资源。相反,您可能想做类似的事情:

resources :news, controller: 'posts' do
   member do
     patch :approve
     patch :reject
   end
end

是的,这会破坏您的测试 - 哇哇。然而,仅仅为了避免更改现有代码/测试而构建糟糕的应用程序并不是一个可行的长期方法。