动态路径辅助方法 Rails

24

自动添加到Rails中的路径有哪些?比如,如果你有一个“Question”资源,那么你会自动获得questions_path、question_path等路径。我在哪里可以看到它们解析为什么以及我得到了什么?

3个回答

43

这一部分可能有所帮助 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)
如果你想为show动作创建一个帮助器,你可以编写
photo_path(@photo.id)

此处的@photo是您的模型对象。或者如果它响应id方法,您可以直接传递@photo

photo_path(@photo)
edit_photo_path(@photo)

你也可以在终端中加载 rails console 并使用 app 测试路由,例如 app.photo_path(1)(它将显示具有 id 等于 1 的照片的路由)


10

直接使用:

rake routes

这将列出所有定义的路由。第一列对于您的路径辅助程序非常重要。


1
这里是关于rake routes命令的详细解释:http://guides.rubyonrails.org/routing.html#seeing-existing-routes-with-rake - Amit Patel
我看不出这怎么展示了我可以将什么作为参数传递给辅助函数等等? - LuckyLuke
针对当前版本的Rails更新@AmitPatel的评论:https://guides.rubyonrails.org/routing.html#inspecting-and-testing-routes - Wodin

0
如果您的路由文件中有以下内容:
resources :questions

然后Rails为您提供以下RESTful路由:

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

你也可以运行 rake:routes 查看正在生成什么。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接