Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between FormHelper::label and FormTagHelper::label_tag?

I'm writing a form which is dealing with multiple models. Some examples of how to do this use ActionView::Helpers::FormHelper::label, and some use ActionView::Helpers::FormTagHelper::label_tag, and I don't really understand the difference.

In my particular case, both seem to result in the same output:

<% form_for :post, :url => { :action => 'create' } do %>
  <p>
    <%= label_tag 'post_type' %><br />
    <%= text_field :post, :post_type %>
  </p>
  <p>
    <%= label :post, :parent_post_id %><br />
    <%= text_field :post, :parent_post_id %>
  </p>
  ...

Renders:

  <p>
    <label for="post_type">Post type</label><br />
    <input id="post_post_type" name="post[post_type]" size="30" type="text" />
  </p>
  <p>
    <label for="post_parent_post_id">Parent post</label><br />
    <input id="post_parent_post_id" name="post[parent_post_id]" size="30" type="text" />
  </p>

The label helper would seem to be more useful, because presumably there are some extra things it can do because it knows the model and property it's labelling, but I can't find anything to back that up. Is there a practical difference between the two? When should I use one helper instead of the other?

like image 995
Jason Owen Avatar asked Jun 18 '09 04:06

Jason Owen


1 Answers

Rails provides two types of form helpers: those that work specifically with model attributes and those that don't. The *_tag helpers are for creating form tags that don't rely on an Active Record object being assigned to the template.

Although there's no difference in the generated markup for a label element as you've shown, in your case you should use the label form helper to be consistent with your use of the other form helpers and because it automatically sets the for attribute to the correct ID of the associated text field element.

like image 122
John Topley Avatar answered Nov 08 '22 09:11

John Topley