Ruby-on-rails 动态路径助手 rails
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11863305/
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
Dynamic path helpers rails
提问by LuckyLuke
What are the paths that is automatically added by Rails? Let say you have a Question resource you automatically get questions_path, question_path etc. Where do I see what they resolve to and what I get?
Rails 自动添加的路径有哪些?假设您有一个 Question 资源,您会自动获得 questions_path、question_path 等。我在哪里可以看到它们解决了什么问题以及我得到了什么?
回答by evfwcqcg
This section might be helpful http://guides.rubyonrails.org/routing.html#specifying-a-controller-to-use
本节可能会有所帮助http://guides.rubyonrails.org/routing.html#specifying-a-controller-to-use
Verb Path Action Helper
GET /photos index photos_path
GET /photos/new new new_photo_path
POST /photos create photos_path
GET /photos/:id show photo_path(:id)
GET /photos/:id/edit edit edit_photo_path(:id)
PUT /photos/:id update photo_path(:id)
DELETE /photos/:id destroy photo_path(:id)
If you want to create a helper for showaction you can write
如果你想为show动作创建一个助手,你可以写
photo_path(@photo.id)
where @photois your model object. Or you can pass @photodirectly if it responds to idmethod.
@photo你的模型对象在哪里。或者@photo如果它响应id方法,您可以直接传递。
photo_path(@photo)
edit_photo_path(@photo)
You can also load rails console(in terminal) and test routes using applike so app.photo_path(1)(it will show you the route for the photo with idequals 1)
您还可以像这样加载rails console(在终端中)和测试路线(它会用equals显示照片的路线)appapp.photo_path(1)id1
回答by thorsten müller
Just use:
只需使用:
rake routes
This will list all routes defined. The first column is relevant for you path helpers.
这将列出所有定义的路由。第一列与您的路径助手相关。
回答by Shailen Tuli
If you have the following in your routes file:
如果您的路由文件中有以下内容:
resources :questions
Then Rails provides the following restful routes for you:
那么Rails 为你提供了以下宁静路线:
GET /questions index list of questions
GET /questions/new new show new question form
POST /questions create create a new question
GET /questions/:id show show a specific question
GET /questions/:id/edit edit show form to edit question
PUT /questions/:id update update a specific question
DELETE /questions/:id destroy delete a specific question
You can also run rake:routes to see what is being generated.
您还可以运行 rake:routes 来查看正在生成的内容。

