Skip to content

Add a tag field to forms in Rails 4.2 and above

Ewerton Miglioranza edited this page Jul 9, 2019 · 6 revisions

In Rails 4.2 and above you must construct the field that accepts the tags the following way:

<%= f.text_field :tag_list, value: f.object.tag_list.join(",") %>

This is because ActionView::Helpers::Tags::TextField no longer calls html_safe on its value, which means that for a post with tag_list ['ruby', 'rails'], the following erb block

<%= f.text_field :tag_list %>

produces

<input type="text" value="ruby rails" name="post[tag_list]" id="post_tag_list">

rather than

<input type="text" value="ruby, rails" name="post[tag_list]" id="post_tag_list">

If using simple_form, correct syntax is:

<%= f.input :tag_list, input_html: {value: f.object.tag_list.join(",")} %>

For more information see #620.

Clone this wiki locally