Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom actions in rails controller with restful actions?

I'm having some trouble with using creating my own actions inside a controller I generated using the scaffold.

I understand everything maps to the restful actions but I'm building a user controller where users can login/logout, etc but when I created the action and declared it in the routes.rb I get this error when I visit users/login

Couldn't find User with id=login

It tries to use login as a ID parameter instead of using it as an action.

Routes.rb

match 'users/login' => 'users#login'

I think I'm doing something wrong with the routes so if anybody could help me that would be great.

Thanks

like image 401
user827570 Avatar asked Jul 06 '12 05:07

user827570


Video Answer


1 Answers

I assume your routes.rb looks like this:

resources :users
match 'users/login' => 'users#login'

The problem is that Rails uses the first route that matches. From the documentation:

Rails routes are matched in the order they are specified, so if you have a resources :photos above a get 'photos/poll' the show action’s route for the resources line will be matched before the get line. To fix this, move the get line above the resources line so that it is matched first.

So either define your custom route before resources :users:

match 'users/login' => 'users#login'
resources :users

…or use this syntax for adding more RESTful actions:

resources :users do
  collection do
    match 'login'
  end
end

To see the existing routes (and their order) run rake routes from the command line.

like image 160
Stefan Avatar answered Sep 30 '22 14:09

Stefan