Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 265
Undistraction Avatar asked Aug 08 '12 15:08

Undistraction


People also ask

What is get and post method in Rails?

Both GET and POST hold intrinsic meaning if you're making an HTML-based API. But in general, GET is used for fetching data, POST is used for submitting data. The biggest difference is that GET puts all the data in the URL (which can be limited in size), while POST sends it as a data part of the HTTP request.

What is render in rails?

What's rendering in Rails? Rendering is the ultimate goal of your Ruby on Rails application. You render a view, usually . html. erb files, which contain a mix of HMTL & Ruby code.


2 Answers

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.

like image 79
hgmnz Avatar answered Nov 15 '22 20:11

hgmnz


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?)
like image 32
PinnyM Avatar answered Nov 15 '22 20:11

PinnyM