我正在努力了解铁路路线。我读过铁路指南,但还是很困惑。例如,我有一个post_controller,所有rails crud操作如下:
posts GET /posts(.:format) posts#index
POST /posts(.:format) posts#create
new_post GET /posts/new(.:format) posts#new
edit_post GET /posts/:id/edit(.:format) posts#edit
post GET /posts/:id(.:format) posts#show
PATCH /posts/:id(.:format) posts#update
PUT /posts/:id(.:format) posts#update
DELETE /posts/:id(.:format) posts#destroy
正如我从上面看到的,只有index, new, edit and show
操作在左边有一个路径名。例如,index
操作的路径名为posts
,我可以将url获取为posts_path
。我可以在链接标签中使用它,如下
<a href="<%= posts_path %>">here</a>
但是,创建、更新和销毁操作没有路径名。那么,在这种情况下,我如何获得下面链接的创建操作的url呢?
<a href="<%= ..... link to create action of post controller %>">here</a>
因此,实际上在所有生成的路由上都有_path助手,我在下面的生成路由前面添加了路径名,我稍后将解释其中的区别:
posts GET /posts(.:format) posts#index
posts POST /posts(.:format) posts#create
new_post GET /posts/new(.:format) posts#new
edit_post GET /posts/:id/edit(.:format) posts#edit
post GET /posts/:id(.:format) posts#show
post PATCH /posts/:id(.:format) posts#update
post PUT /posts/:id(.:format) posts#update
post DELETE /posts/:id(.:format) posts#destroy
因此,您向服务器发出的任何GET请求都可以使用给定的路径来完成(因为GET是任何已访问链接的默认路径),但您仍然可以使用_path助手来访问其他路由,方法是明确说明要使用的方法。例如:
Index:
<%= link_to "Index", posts_path %>
Create:
<%= link_to "Create", posts_path, method: 'POST' %>
New:
<%= link_to "New", new_post_path %>
Edit:
<%= link_to "Edit", edit_post_path(post_id) %>
Show:
<%= link_to "Show", post_path(post_id) %>
Update:
<%= link_to "Update", post_path(post_id), method: 'POST' %>
<%= link_to "Update", post_path(post_id), method: 'PATCH' %>
Destroy:
<%= link_to "Destroy", post_path(post_id), method: 'DELETE' %>
传递要删除的帖子或要创建的对象的路径和id:
<%= link_to posts_path(@post) %>
如果你在一个表单中,并且有一个对象(@post=post.new)rails会在提交时根据你使用该路由提交表单的事实知道你想要创建的对象。如果你想使用link_to删除,你需要通过method: :delete
您需要在link_to
方法中使用method
属性。路由名称是相同的,但只是使用了不同的HTTP谓词:
<%= link_to "Update Post", post_path, method: :patch %>
我向你推荐这门课,对我来说,这对我理解这一点有很大帮助。但基本上你需要发送方法put,patch或delete铁轨上的路线说明,轨道的补丁和放置
<%= link_to "Update Post", posts_path(@post.id), method: :patch %>
<%= link_to "Update Post", posts_path(@post.id), method: :put %>
<%= link_to "delete Post", posts_path(@post.id), method: :delete%>
不要忘记id很重要,因为你的管理员需要知道需要更新或删除什么帖子。