How do rails decide to make a form using the PUT or POST method?

Rails generates a partial form that can be used both on the page displayed by the get action and on the page created by the new action. If this is the first form method set to PUT, if the last to form action is set to POST.

How do rails decide which method to use?

+7
source share
2 answers

if the object submitted to the form is persisted? , the form designer knows that you are updating the object and therefore t21> action. If it is not saved, then it knows that you are creating a new object and it will use POST .

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

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

+12
source

Formatting existing resources uses PUT , forms a new POST resource. REST compliant is described here .

From 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?) 
+3
source

All Articles