在 rails 路线中获取正确的 ID

Getting correct ID in rails route

当我做一个rake routes时,

GET       test/:test_id/associated_link(.:format)
GET       test/(.:format)
POST      test/(.:format)
GET       test/new(.:format)
GET       test/:id/edit(.:format)
PATCH     test/:id(.:format)
PUT       test/:id(.:format)
DELETE    test/:id(.:format)

我需要第一个实例进行测试/:id/associated_link

路由文件看起来像

Rails.application.routes.draw do
   resources :years
   resources :mateirals
   resources :people
   resources :jobs
   resources :test do
     get 'associated_links'
   end

   root 'welcome#index'
   resources :welcome, :companies, :positions

应该是成员路由

   resources :test do
     member do
         get 'associated_links'
     end
   end

您可以使用 member route,它可以在文档中找到。它看起来像这样:

resources :test do 
  member do
    get 'associated_links'
  end
end

或者,如果你只有一个成员路由,你可以这样消除阻塞:

resources :test do 
  get 'associated_links', on: :member
end

如果您希望 URI 模式看起来像 test/:id/associated_link,您需要更改

resources :test do
   get 'associated_links'
end

resources :test do
   get 'associated_links', on: :member
end

已测试