Monday 8 April 2013

form_for and form_tag

I would like to explain differences between form_for and form_tag

form_tag and form_for both are used to submit the form and it’s elements. The main difference between these two is the way of managing objects related to that particular model is different.

form_for:

We should use “form_for” tag for a specific model i.e. while crating a new row in database. It performs the “standard http post” which is having fields related to active record (model) objects.

Example for how to use form_for tag:

<% form_for :user, @user, :url => { :action => "update" } do |f| %>

After this, we can use the f as an object to create input filed.

Username: <%= f.text_field :username %>
Email : <%= f.text_field :email %>
Address: <%= f.text_area :address %>

<% end %>

form_tag:

It creates a form as a normal form. form_tag also performs the “standard http post” without any model backed and has normal fields. This is mainly used when specific data need to be submitted via form.


Example:

<% form_tag '/articles' do -%>
<%= text_field_tag "article", "firstname" %>
<% end -%>

It just creates a form tag and it is best used for non-model forms.

No comments:

Post a Comment