15

我有一个具有许多操作的控制器:

class TestsController < ApplicationController
   def find
   end

   def break
   end

   def turn
   end
end

当我像这样将它添加到我的routes.rb文件中时:

resources :tests

并执行rake routes我看到以下额外回合的任务:

    tests GET    /tests(.:format)          tests#index
          POST   /tests(.:format)          tests#create
 new_test GET    /tests/new(.:format)      tests#new
edit_test GET    /tests/:id/edit(.:format) tests#edit
     test GET    /tests/:id(.:format)      tests#show
          PUT    /tests/:id(.:format)      tests#update
          DELETE /tests/:id(.:format)      tests#destroy

显然我的控制器没有上述动作。那么我如何告诉 Rails 避免生成/期望这些路由呢?

4

3 回答 3

39

只需为没有 CRUD 的未来简单的路线添加答案:

resources :tests, only: [] do 
  collection do 
    get 'find'
    match 'break'
    match 'turn'
  end 
end

# output of rake routes

find_tests GET /tests/find(.:format)  tests#find
break_tests     /tests/break(.:format) tests#break
turn_tests     /tests/turn(.:format)  tests#turn

或使用namespace代替resources

namespace :tests do
  get 'find'
  match 'break'
  match 'turn'
end

# output of rake routes

tests_find GET /tests/find(.:format)  tests#find
tests_break     /tests/break(.:format) tests#break
tests_turn     /tests/turn(.:format)  tests#turn

对于 Rails 4。(原因match 方法已在 rails 4.x 或最新版本中被弃用)

resources :tests, only: [] do 
  collection do 
    get 'find'
    get 'break'
    get 'turn'
  end 
end

采用namespace

namespace :tests do
  get 'find'
  get 'break'
  get 'turn'
end
于 2013-07-12T09:47:20.810 回答
11

您可以像这样指定要路由的操作:

resources :tests, except: [:new, :create, :edit, :update, :destroy] do 
  collection do 
    get 'find'
    get 'break'
    get 'turn'
  end 
end
于 2013-07-04T08:33:21.793 回答
1

如果您不想要宁静的路线,请不要使用resources,请自行指定每个路径和操作。

get '/tests/find' => 'tests#find'
post '/tests/break' => 'tests#break'
post '/tests/turn' => 'tests#turn'

你像这样指定参数:

post '/tests/add/:id' => 'tests#add'
于 2013-07-04T08:44:32.120 回答