ruby-on-rails - 如何在没有 CRUD 操作的情况下路由 Controller ?

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

我有一个包含许多操作的 Controller :

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

显然我的 Controller 没有上述 Action 。那么我该如何告诉 Rails 避免生成/期望这些路由呢?

最佳答案

只需为 future 添加一个答案,无需 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。(在 rails 4.x 或最新版本中导致 match method has been deprecated)

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

使用命名空间

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

关于ruby-on-rails - 如何在没有 CRUD 操作的情况下路由 Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17465335/

相关文章:

ruby-on-rails - 在哪里可以找到 ruby​​ on Rails 应用程序的部署日志文件

ruby-on-rails - Rails JSON 到 Swift 2 JSON

ruby - Ruby 模块是否可以定义类方法,以便它们在模块嵌套时也能工作?

ruby-on-rails - 计算 Rails 中记录之间的平均天数

ruby-on-rails-3 - AngularJS View 在 Rails 应用程序中的位置

ruby-on-rails - 水星 : SyntaxError: cannot return a value from a constructor

ruby-on-rails - RoR : Enums, 如何根据他们列出消息的收件人

ruby-on-rails - %w{ 模型 }.each 做 |dir|在 Rails 中是什么意思?

ruby - 在 URI 上设置包含 [ ] 的路径

ruby-on-rails - 删除has_many :through join records?的正确方法