简体   繁体   English

使用restful操作在rails控制器中自定义操作?

[英]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. 我在使用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 我理解一切都映射到了宁静的动作,但我正在构建一个用户控制器,用户可以登录/注销等,但是当我创建动作并在routes.rb中声明它时,当我访问用户/登录时出现此错误

Couldn't find User with id=login

It tries to use login as a ID parameter instead of using it as an action. 它尝试使用login作为ID参数,而不是将其用作操作。

Routes.rb 的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 谢谢

I assume your routes.rb looks like this: 我假设您的routes.rb看起来像这样:

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

The problem is that Rails uses the first route that matches. 问题是Rails使用匹配的第一个路由。 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. Rails路由按照指定的顺序进行匹配,因此如果您有resources :photos get 'photos/poll'之上的get 'photos/poll'resources行的show action路线将在get行之前匹配。 To fix this, move the get line above the resources line so that it is matched first. 要解决此问题,请将get行移到resources上方 ,以便首先匹配。

So either define your custom route before resources :users : 因此,要么 resources :users 之前定义自定义路由resources :users

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

…or use this syntax for adding more RESTful actions : ...或使用此语法添加更多RESTful操作

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

To see the existing routes (and their order) run rake routes from the command line. 要查看现有路由(及其顺序),请从命令行运行rake routes

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM