为什么rails scaffold在创建,更新和销毁操作中使用respond_to块?

时间:2022-02-09 01:23:25

From what I understand, these actions are usually triggered after a form is submitted. I can't imagine any reason why a form would generate json, in other words, (assuming a hypothetical controller is named 'UsersController') I can't imagine when or how a form would take my browser to:

根据我的理解,这些操作通常在提交表单后触发。我无法想象为什么表单生成j​​son的任何原因,换句话说,(假设一个假设的控制器被命名为'UsersController')我无法想象表单何时或如何将我的浏览器带到:

localhost:3000/users.json

wouldn't post requests automatically take the user to:

不会发布请求自动将用户带到:

localhost:3000/users

...and hence automatically to html? And furthermore, if they arrived here, at:

...因此自动转到HTML?而且,如果他们到达这里,请:

localhost:3000/users

and typed in:

并输入:

localhost:3000/users.json

wouldn't this just be a GET request back to index.json? And hence back to the index action?...rendering json in that particular action via a GET request (not the create action, via POST)?

这不是一个GET请求回到index.json?因此回到索引操作?...通过GET请求(而不是创建操作,通过POST)在该特定操作中呈现json?

I'm confused and can't understand how anyone could ever end up at users.json from a POST request, and hence I can't imagine why a respond_to block that renders json makes sense in these actions. What am I missing?

我很困惑,无法理解任何人最终会如何从POST请求中结束users.json,因此我无法想象为什么呈现json的respond_to块在这些操作中有意义。我错过了什么?

1 个解决方案

#1


Rails assumes that the controller actions might also be accessed as an API and not just via the browser. In such cases it makes sense to respond to those requests differently instead of redirecting the client (browser) to the index or show action.

Rails假定控制器操作也可以作为API访问,而不仅仅通过浏览器访问。在这种情况下,以不同方式响应这些请求而不是将客户端(浏览器)重定向到索引或显示操作是有意义的。

When you create a resource from an API client, it might not make sense to redirect the user to the index or show action instead of just responding to the client that the resource was created (or not). Same applies for the update and destroy actions.

当您从API客户端创建资源时,将用户重定向到索引或显示操作可能没有意义,而不是仅响应创建资源的客户端(或不响应)。同样适用于更新和销毁操作。

#1


Rails assumes that the controller actions might also be accessed as an API and not just via the browser. In such cases it makes sense to respond to those requests differently instead of redirecting the client (browser) to the index or show action.

Rails假定控制器操作也可以作为API访问,而不仅仅通过浏览器访问。在这种情况下,以不同方式响应这些请求而不是将客户端(浏览器)重定向到索引或显示操作是有意义的。

When you create a resource from an API client, it might not make sense to redirect the user to the index or show action instead of just responding to the client that the resource was created (or not). Same applies for the update and destroy actions.

当您从API客户端创建资源时,将用户重定向到索引或显示操作可能没有意义,而不是仅响应创建资源的客户端(或不响应)。同样适用于更新和销毁操作。