Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to route 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 file like so:

resources :tests

and execute the rake routes task I see the following extra 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 doesn't have the above actions. So how do I tell Rails to avoid generating/expecting those routes?

like image 350
Roman Avatar asked Jul 04 '13 08:07

Roman


3 Answers

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
like image 166
rails_id Avatar answered Sep 21 '22 06:09

rails_id


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
like image 37
a.s.t.r.o Avatar answered Sep 19 '22 06:09

a.s.t.r.o


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'
like image 41
ctcherry Avatar answered Sep 19 '22 06:09

ctcherry