本文介绍了动态路径助手 rails的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Rails 自动添加的路径有哪些?假设您有一个 Question 资源,您会自动获得 questions_path、question_path 等.我在哪里可以看到它们解决了什么问题以及我得到了什么?

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?

推荐答案

本节可能会有帮助 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 动作创建一个助手,你可以写

If you want to create a helper for show action you can write

photo_path(@photo.id)

其中 @photo 是您的模型对象.或者你可以直接传递 @photo 如果它响应 id 方法.

where @photo is your model object. Or you can pass @photo directly if it responds to id method.

photo_path(@photo)
edit_photo_path(@photo)

您还可以像 app.photo_path(1) 一样加载 rails 控制台(在终端中)并使用 app 测试路由(它将向您展示 id 等于 1)

You can also load rails console (in terminal) and test routes using app like so app.photo_path(1) (it will show you the route for the photo with id equals 1)

这篇关于动态路径助手 rails的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 13:52