Sam D20
Sam D20

Reputation: 2575

What exactly is going on when form_for is called in rails?

<%= form_for(@user) do |f| %>

  <%= f.label :name %>
  <%= f.text_field :name %>

  <%= f.label :email %>
  <%= f.text_field :email %>

  <%= f.label :password %>
  <%= f.password_field :password %>

  <%= f.label :password_confirmation, "Confirmation" %>
  <%= f.password_field :password_confirmation %>

  <%= f.submit "Create my account", class: "btn btn-large btn-primary" %>
<% end %>

If this code is embedded into an html document and that html document is requested, is form_for only called once to return the form in HTML for that page?

Most importantly, What is being passed in for f in the block? What is the purpose of it?

edit: also, what is responsible for passing in f?

Upvotes: 1

Views: 64

Answers (3)

Gagan Gami
Gagan Gami

Reputation: 10251

In block of form |f| is a form builder object. So you don't need to write again and again form_for. It is called for method like textfield, radio button, label, submit button for that form. You can replace f with any other word or character.

Upvotes: 0

chandra
chandra

Reputation: 1

the f variable is used to called helper methods like label,textfield and submit buttons for that form.please see the generated html source in browser.

Upvotes: 0

Austio
Austio

Reputation: 6085

seems like you are a little new to the magic of rails, so i understand your question.

Form_For does many things, at it's most basic level it generates the proper html for RESTful interaction with your web server. Where it goes a step further is it determines if @user is a new model or one that already exists. If it is a new model, it sends the request to your new action as a post. If @user already exists in your database it sets up all the right things for your webpage to do an update on the record.

To get a better grasp I recommend checking out codeschool.com rails for zombies, it will probably help you alot. Or read http://guides.rubyonrails.org/form_helpers.html

|f| is a ruby block and it yeilds a form builder object (which is f) and then the methods like .lable, or .submit are called on that form builder object.

The form builder object is aware of your @user because you pass it in, so it is able to make intelligent decisions about whether it is a new model or a current model because of that.

Hope that helps.

Upvotes: 1

Related Questions