【问题标题】:Rails 5 tags array turning into stringRails 5标签数组变成字符串
【发布时间】:2017-01-13 20:34:00
【问题描述】:

BLUF:我的帖子标签数组可以很好地创建和读取标签,但是当我编辑帖子时,表单字段会删除标签数组的逗号;用户必须手动将逗号重新输入到标签字段中,即使他们没有更新它,否则标签会以一个长字符串连接在一起。

详细信息:使用 rails 5 和acts_as_taggable_on gem。

我的帖子模型

class Post < ApplicationRecord

  acts_as_taggable

在我的控制器中:

   private

   def post_params
     params.require(:post).permit(:post_type, :title, :content, :picture, :body_parts,
                                  :duration, :equipment, :calories, :protein,
                                  :fat, :carbs, :ingredients, tag_list:[] )
   end

在我的表单视图中:

 <%= form_for(@post, html: { multipart: true }) do |f| %>
      <%= render 'shared/error_messages', object: f.object %>

          <span class="glyphicon glyphicon-tags"></span>
          <%= f.text_field :tag_list, multiple: true, class: 'form-control' %>

      <%= f.submit "Save changes", class: "btn btn-primary" %>
      <%= link_to "Cancel", post_path(@post), class: "btn btn-default" %>

      <% end %>

在帖子显示视图中:

  <%= raw post.tag_list.map { |t| link_to t, tag_path(t) }.join(', ') %>

我不知道还有什么相关的,但就像我说的,一切正常,直到我尝试编辑帖子,然后 text_field 去掉逗号

提前感谢您的任何建议,

【问题讨论】:

    标签: ruby-on-rails arrays ruby tags ruby-on-rails-5


    【解决方案1】:

    将标签添加到text_fieldvalue 参数并将它们转换为逗号分隔符字符串。

    <%= f.text_field :tag_list, value: f.object.tag_list.to_s, multiple: true, class: 'form-control' %>
    

    【讨论】:

    • 第一个帖子,最好的帖子!
    猜你喜欢
    • 2012-09-16
    • 1970-01-01
    • 2015-06-24
    • 2019-07-18
    • 1970-01-01
    • 1970-01-01
    • 2020-08-17
    • 2023-03-16
    • 1970-01-01
    相关资源
    最近更新 更多