How does rails decide to render a form with a method of PUT or POST?

ぐ巨炮叔叔 提交于 2019-12-18 12:34:44

问题


Rails generates a form partial that can be used on both the page rendered by a get action and a page rendered by a new action. If it is the former the form's method is set to PUT, if the latter the form's action is set to POST.

How does rails decide which method to use?


回答1:


if the object passed to the form is persisted?, the form builder knows that you are updating an object and will therefore render a PUT action. If it is not persisted, then it knows you are creating a new object and it will use POST.

<%= form_for @user do |f| %>
  <%= f.button %>
<% end %>

If @user is a new record, POST is used and the button label becomes Create User, otherwise PUT is used and the label becomes Update User. There's not much more to it.




回答2:


Forms editing existing resources use PUT, forms creating a new resource use POST. As per REST standards described here.

From the rails form_for helper code:

action, method = object.respond_to?(:persisted?) && object.persisted? ? [:edit, :put] : [:new, :post]

and persisted? for ActiveRecord is declared as:

!(new_record? || destroyed?)


来源:https://stackoverflow.com/questions/11868489/how-does-rails-decide-to-render-a-form-with-a-method-of-put-or-post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!