How to manage controllers without CRUD actions?

I have a controller with a number of actions:

class TestsController < ApplicationController def find end def break end def turn end end 

When I add it to my routes.rb as follows:

 resources :tests 

and complete the rake routes task, I see the following additional rounds:

  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 

Obviously, my controller does not have the above actions. So, how can I tell Rails to avoid generating / waiting for these routes?

+7
source share
3 answers

You can specify the actions you want to take as follows:

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

Just add an answer for future simple route paths 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. (the reason the matching method is deprecated in rails 4.x or later)

 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 
+27
source

If you do not want calm routes, do not use resources , specify each path and action on it.

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

And you set these parameters:

 post '/tests/add/:id' => 'tests#add' 
+1
source

Source: https://habr.com/ru/post/948686/


All Articles