Custom actions in rails controller with restful actions?

此生再无相见时 提交于 2019-12-10 14:16:29

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/11356453/custom-actions-in-rails-controller-with-restful-actions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!