Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does form_for knows what URL/path to go when the submit button is clicked?

I'm creating a scaffold named User. I checked the code of the partial view "_form" and I see the code snippet below:

<%= form_for(user) do |f|  %>
   <div class=field>
      <%= f.label :firstname %>
      <%= f.text_field :firstname %>
   </div>
   <div class="actions">
      <%= f.submit %>
   </div>
<% end %>

So if you click the submit button generated by the code above, how does rails know what URL/path to go since it didn't specify there what path to look for?

like image 850
Lou Avatar asked Sep 06 '25 02:09

Lou


2 Answers

Apart from Amr El Bakry's answer, let me help you demystifying the Rails magic behind the form_for helper method.

So your question is basically: how does form_for find out the route to submit to and how does it distinguish between creating/updating the record?

Rails actually sorts this out through record identification. An example is worthy at this point:

## Creating a new user
# long style
form_for(@user, url: users_path)
# short style - record identification gets used
form_for(@user)

## Updating an existing user
# long style
form_for(@user, url: user_path(@user), html: { method: "patch" })
# short style - record identification to the rescue
form_for(@user)

You can clearly see that the short style is the same for both cases. Record identification is smart enough to figure out if the record is new or an existing one by invoking @user.persisted?.

You may be interested to assert this fact yourself in the form_for definition inside the form_helper.rb on line 462 !

Hope it helps!

like image 123
Wasif Hossain Avatar answered Sep 09 '25 05:09

Wasif Hossain


In your config/routes.rb file, you'll find Rails has added resources :users when you generated the scaffold. This is called a resourceful route, and it creates seven different routes for your user resource; each route maps an HTTP verb and a URL to a controller action.

In your case, when you submit the form, the HTTP verb is POST, the path is /users mapped to the create action inside the users controller. This is Rails default and you can read all about it in the Rails Guides on Routing.

like image 30
amrrbakry Avatar answered Sep 09 '25 07:09

amrrbakry