首页 > 解决方案 > 在 Rails 5.2 应用程序中使用 Postgres 数组列时清除表单字段的最佳实践?

问题描述

我正在构建一个 Rails 5.2 应用程序,它有一个 Postgres 数组列来在 Post 模型上存储标签。我创建的迁移看起来像这样......

class AddTagsToPosts < ActiveRecord::Migration[5.2]
  def change
    change_table :posts do |t|
      t.string :tags, array: true, default: []
    end
  end
end

由于需要设置默认值(?...我未能找到一种方法让 PG 数组列工作而不将标签的默认值设置为空数组),删除默认值的最佳做法是什么( []) 在不使用 JS 的情况下自动填写 Rails 新/编辑表单?

标签: ruby-on-railspostgresql

解决方案


<% 3.times do |num| %>
  <%= form.text_field :tags, multiple: true, class: "form-control", value: @post.tags[num] %>
<% end %>

推荐阅读