How to route controllers without CRUD actions?

前端 未结 3 1420
我寻月下人不归
我寻月下人不归 2021-01-01 22:12

I have a controller with a number of actions:

class TestsController < ApplicationController
   def find
   end

   def break
   end

   def turn
   end
en         


        
相关标签:
3条回答
  • 2021-01-01 22:27

    Just add an answer for future, simple ways of route without 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
    

    or use namespace instead of 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. (cause match method has been deprecated in rails 4.x or latest)

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

    use namespace

    namespace :tests do
      get 'find'
      get 'break'
      get 'turn'
    end
    
    0 讨论(0)
  • 2021-01-01 22:37

    You can specify actions you want to route like this:

    resources :tests, except: [:new, :create, :edit, :update, :destroy] do 
      collection do 
        get 'find'
        get 'break'
        get 'turn'
      end 
    end
    
    0 讨论(0)
  • 2021-01-01 22:40

    If you don't want the restful routes, don't use resources, specify each path and action on it's own.

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

    And you specify params like so:

    post '/tests/add/:id' => 'tests#add'
    
    0 讨论(0)
提交回复
热议问题