简体   繁体   English

为什么在rails中不存在删除/销毁的直接路径?

[英]Why doesn't direct path for delete/destroy exist in rails?

When you define a link_to in rails to delete an object/item you must specify method delete in that link_to, as compared to edit (edit_event_path(@event)) or show (event_path). 在rails中定义link_to以删除对象/项时,必须在该link_to中指定方法delete,与edit(edit_event_path(@event))或show(event_path)相比。 Why is this the case? 为什么会这样?

In typical link_to links the browser will send HTTP GET requests. 在典型的link_to链接中,浏览器将发送HTTP GET请求。 When you're destroying a resource the browser should send a HTTP DELETE request. 当您销毁资源时,浏览器应发送HTTP DELETE请求。 Rails has some javascript that will run on those links and intercept the click to send a HTTP DELETE request for those marked with method: :delete. Rails有一些javascript将在这些链接上运行并截取单击以发送标记为method :: delete的HTTP DELETE请求。 Also the path for a single resource to be destroyed and shown will be the same. 此外,单个资源被销毁和显示的路径也是相同的。

event_path will return "/event/1" or similar. event_path将返回“/ event / 1”或类似内容。 When sending a HTTP GET request its expected that the show action of your controller will be called. 发送HTTP GET请求时,预计将调用控制器的show动作。 When sending a HTTP DELETE request to the same path its expected that the destroy action will be called. 将HTTP DELETE请求发送到同一路径时,预期将调用destroy操作。

HTTP Verbs HTTP动词

Simply, Rails makes use of the HTTP Verbs which governs the web 简单地说,Rails使用管理Web的HTTP Verbs

Essentially, to keep routing structures simple, Rails allows you to generate a series of the "same" URL paths, each defined with different http verbs : 本质上,为了保持路由结构的简单,Rails允许您生成一系列“相同”的URL路径,每个路径都使用不同的http verbs定义:

在此输入图像描述

This means if you want to destroy an object, you can use the delete verb 这意味着如果要destroy对象,可以使用delete动词

-- -

OOP OOP

A more specific definition for this lies with the object-orientated structure of Ruby (& Rails). 对此更具体的定义在于Ruby(&Rails) 的面向对象结构。 The routing system is based around this structure (hence why they're called resources ) - meaning if you treat the routing system as based around objects , you can begin to see a pattern emerge 路由系统基于这种结构(因此它们被称为resources ) - 这意味着如果您将路由系统视为基于对象 ,您可以开始看到模式出现

If you're going to call a route for an object, IE to destroy that object, your route should be for the "object", not the "destroy" mechanism 如果你打算为一个对象调用route ,IE要destroy该对象,你的路径应该是“对象”,而不是“破坏”机制

In this sense, if you want to destroy an object, it makes much more sense to use the following: 从这个意义上说,如果你想破坏一个对象,使用以下内容会更有意义:

<%= link_to "Destroy", object_path(object), method: :delete %>

This gives you the flexibility to create actions around objects, which can then be routed to the particular controller#actions as required 这使您可以灵活地围绕对象创建操作,然后可以根据需要将其路由到特定的控制器#操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM