【问题标题】:Rails 5 ActiveRecord Update Serialized Array in FormRails 5 ActiveRecord 以形式更新序列化数组
【发布时间】:2017-06-22 17:23:46
【问题描述】:

我有一个序列化数组的字段。它已加载到我的模型中并以以下形式访问:

class Site < ApplicationRecord
  serialize :steps, Array
end


<table class="listing" summary="Site list">
    <tr class="header">
      <th>Name</th>
      <th>Step 1</th>
      <th>Step 2</th>
      <th>Step 3</th>
      <th>Actions</th>
    </tr>
    <% @sites.each do |site| %>
    <tr>
      <td><%= site.name %></td>
      <% site.steps.each do |step| %>
      <td><%= step %></td>
      <% end %>
      <td class="actions">
        <%= link_to("Show", site_path(site), :class => 'action show') %>
        <%= link_to("Edit", edit_site_path(site), :class => 'action edit') %>
        <%= link_to("Delete", delete_site_path(site), :class => 'action delete') %>
      </td>
    </tr>
    <% end %>
  </table>

我正在尝试更新我的编辑表单,以便可以编辑数组中的每个“步骤”。

 <%= form_for(@site) do |f| %>

    <table summary="Site form fields">
      <tr>
        <th>Name</th>
        <td><%= f.text_field(:name) %></td>
      </tr>
      <% a=1 %>
      <% @site.steps.each do |step| %>
      <tr>
      <th>Step <%= a %>
      <td><%= text_field :site, :steps, :value => step %></td>
      <% a += 1 %>
      </tr>
      <% end %>
    </table>

    <div class="form-buttons">
      <%= f.submit("Update Site") %>
    </div>

  <% end %>

编辑表单将步骤字段正确显示为数组中的每个单独的字符串。但是,当我尝试提交表单时,出现以下错误:

Attribute was supposed to be a Array, but was a String.

因此,步骤将作为数组中的最后一个条目提交。 如何正确显示表单并将更新后的数组返回给控制器进行处理?

【问题讨论】:

    标签: ruby-on-rails arrays forms activerecord


    【解决方案1】:

    您的text_field 需要将multiple 设置为true。我相信你的情况,这样的事情应该有效。

    <%= f.text_field(:steps, { multiple: true, value: @site.steps[step] }) %>
    

    【讨论】:

      猜你喜欢
      • 2013-12-22
      • 2017-03-07
      • 1970-01-01
      • 2010-11-21
      • 2018-06-19
      • 2015-09-18
      • 2012-12-05
      • 2018-02-08
      • 2011-04-30
      相关资源
      最近更新 更多