Ruby on Rails:添加新路由
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13145696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby on Rails : add a new route
提问by socksocket
I'm new with RoR so this is a newbie question:
if I have a controller users_controller.rband I add a method foo, shouldn't it create this route?
我是 RoR 新手,所以这是一个新手问题:
如果我有一个控制器users_controller.rb并且我添加了一个方法foo,它不应该创建这条路线吗?
because when I did that, I got this error:
因为当我这样做时,我收到了这个错误:
Couldn't find User with id=foo
找不到 id=foo 的用户
I of course added a view foo.html.erb
我当然添加了一个视图 foo.html.erb
EDIT:
I added to routes.rbthis code but I get the same error:
编辑:
我添加routes.rb到此代码,但我收到相同的错误:
resources :users do
get "signup"
end
回答by Scott S
This doesn't work automatically in rails 3. You'll need to add
这在 rails 3 中不会自动工作。您需要添加
resource :users do
get "foo"
end
to your routes.rb
到你的routes.rb
You'll definitely want to have a look at http://guides.rubyonrails.org/routing.html, it explains routing pretty well.
你肯定想看看http://guides.rubyonrails.org/routing.html,它很好地解释了路由。
回答by ?V -
Rails is directing you to the show controller and thinks that you're providing foo as :id param to the show action.
Rails 将您引导至 show 控制器,并认为您将 foo 作为 :id 参数提供给 show 操作。
You need to set a route that will be dispatched prior to being matched as /users/:id in users#show
您需要设置一个路由,该路由将在被匹配为 /users/:id in users#show 之前被调度
You can accomplish this by modifying config/routes.rbby adding the following to replace your existing resource describing :users
您可以config/routes.rb通过添加以下内容来替换您现有的资源描述来完成此操作:users
resource :users do
get "foo"
end
回答by mikej
Just to add to the other answers, in earlier versions of Rails there used to be a default route
只是为了添加其他答案,在早期版本的 Rails 中曾经有一个默认路由
match ':controller(/:action(/:id))(.:format)'
which gave the behaviour you describe where a request of the form controller/actionwould call the given method on the given controller. This line is still in routes.rbbut is commented out by default. You can uncomment it to enable this behaviour but the comment above it explains why this is not recommended:
这给出了您描述的行为,表单控制器/操作的请求将在给定控制器上调用给定方法。该行仍然存在,routes.rb但默认情况下已被注释掉。您可以取消注释以启用此行为,但上面的注释解释了为什么不建议这样做:
# This is a legacy wild controller route that's not recommended for RESTful applications.
# Note: This route will make all actions in every controller accessible via GET requests.
回答by creep3007
At the schema ':controller/:action(.:format)', you can also easily do the following
在架构中':controller/:action(.:format)',您还可以轻松地执行以下操作
resources :users do
get "foo", on: :collection
end
or
或者
resources :users do
collection do
get 'foo'
end
end
http://guides.rubyonrails.org/routing.html#adding-collection-routes
http://guides.rubyonrails.org/routing.html#adding-collection-routes

