【问题标题】:How correctly use :path_names in rails routes?如何在 Rails 路线中正确使用 :path_names?
【发布时间】:2016-07-04 22:37:27
【问题描述】:

我正在编写 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 的方法。

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

  • domain.com/newsdomain.com/news/all(得到posts#index
  • domain.com/news/12domain.com/news/preview/12(得到posts#show
  • domain.com/news/newdomain.com/news/request(得到posts#new

我正在尝试使用 :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

请帮我解决它。 谢谢!

【问题讨论】:

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


    【解决方案1】:

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

    resources :news, controller: 'posts' do
    
    end
    

    当涉及到你们其他人的问题时,也许你应该学习 RESTful 默认值的方法和原因。

    使用/news/all 非常独特 - 在 REST 中,它暗示如果路径描述了资源,而不是“根”应该显示所有项目。

    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
    

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

    【讨论】:

      猜你喜欢
      • 2014-12-31
      • 2017-02-13
      • 1970-01-01
      • 2012-02-02
      • 2017-08-20
      • 2015-02-22
      • 1970-01-01
      • 2021-08-27
      • 1970-01-01
      相关资源
      最近更新 更多