如何在没有CRUD操作的情况下路由控制器

时间:2013-07-04 08:23:13

标签: ruby-on-rails ruby ruby-on-rails-3

我有一个控制器,其中包含许多操作:

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避免生成/期望这些路由?

3 个答案:

答案 0 :(得分:29)

只需为没有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

for Rails 4.(导致{4. 3}在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

答案 1 :(得分:10)

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

resources :tests, except: [:new, :create, :edit, :update, :destroy] do 
  collection do 
    get 'find'
    get 'break'
    get 'turn'
  end 
end

答案 2 :(得分:1)

如果您不想使用其他路线,请不要使用resources,请指定每条路径和操作。

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

你指定params如下:

post '/tests/add/:id' => 'tests#add'