What is the difference between FormHelper::label a

2020-04-02 18:58发布

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?

2条回答
Emotional °昔
2楼-- · 2020-04-02 19:39

Use f.label when you are inside a form object created with form_for(...) do |f| and want to refer to a model-attribute. If your app is i18n-ed, Rails will use the translation to display the attribute name.

Use label_tag when you are not in a form object. (Or you are in a form object but want to create a dummy label for a non-model attribute.)

All form inputs have these two variants, with and without the _tag suffix, like select and select_tag, etc

查看更多
Melony?
3楼-- · 2020-04-02 19:49

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.

查看更多
登录 后发表回答