Rails 4: text_field for acts_as_taggable_on not separating tags with a comma

故事扮演 提交于 2019-11-30 03:53:06

问题


I am trying to get the text_field in my form partial to comma-separate acts_as_taggable_on tags. Right now, when I reload the page, the commas disappear so if a field has two or more tags, they become one big tag instead. For instance, I get "Tag1 Tag2 Tag3" instead of "Tag1, Tag2, Tag3". I am using acts-as-taggable-on 3.4.2.

Here is my _form.html.erb partial:

<h2>Tags:</h2>
<p>Please separate the tags with a comma ','</p>

<% @article.tag_types.each do |tag| %>
  <div class="form-group">
    <strong><%= label_tag tag.to_s.titleize %></strong><br />
    <%= f.text_field "#{tag.to_s.singularize}_list".to_sym, :placeholder => "Comma-separated list of #{tag.to_s}", class: 'form-control' %>
  </div>
<% end %>

Every time I reload the edit page, the input value somehow removes the commas from the already-present tags, so the text field looks like this:

<input id="article_country_list" class="form-control" type="text" name="article[country_list]" value="China U.S.A." placeholder="Comma-separated list of countries">

instead of having value="China, U.S.A." as it should be.

Here is my model, article.rb:

class Article < ActiveRecord::Base
  acts_as_taggable_on :people, :cities, :countries, :other
end

Any help would be much appreciated :)

Thanks!


回答1:


Apparently this is a new security feature.

I solved the comma separation issue by doing:

<% @article.tag_types.each do |tag| %>
<div class="form-group">
  <strong><%= f.label tag.to_s.titleize %></strong><br />
  <% tag_sym = "#{tag.to_s.singularize}_list".to_sym %>
  <% tag_list = "#{tag.to_s.singularize}_list" %>
  <%= f.text_field tag_sym, value: @article.send(tag_list).to_s, :placeholder => "Comma-separated list of #{tag.to_s}", class: 'form-control' %>
</div>
<% end %>



回答2:


Thanks! Since I am using ActiveAdmin with Formtastic I made a custom input.

So I created a new class: app/inputs/tag_list_input.rb with:

class TagListInput < Formtastic::Inputs::StringInput
  def input_html_options
    super.merge(:value => "#{@object.send(method).to_s.html_safe}")
  end
end

and using this like:

f.input :some_tag_list, :as => :tag_list, :label => "SomeTags"


来源:https://stackoverflow.com/questions/27646714/rails-4-text-field-for-acts-as-taggable-on-not-separating-tags-with-a-comma

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!