【问题标题】:How do you use simple_form with nested ActiveModel objects (not ActiveRecord)?如何将 simple_form 与嵌套的 ActiveModel 对象(不是 ActiveRecord)一起使用?
【发布时间】:2019-09-13 08:55:25
【问题描述】:

我正在尝试使用 simple_formActiveModel 对象来验证表单数据,然后再使用该数据执行工作。该数据不会被持久化到数据库中,因此不使用ActiveRecord

型号:

class SomeForm
  include ActiveModel::Model

  attr_accessor :name, :items

  validates :name, presence: true
end

class SomeFormItem
  include ActiveModel::Model

  attr_accessor :name

  validates :name, presence: true
end

控制器:

def new
  @form = SomeForm.new
  @form.items = [SomeFormItem.new, SomeFormItem.new]
end

查看

<%= simple_form_for @form, url: some_destination_path do |f| %>
  <%= f.input :name %>
  <%= simple_fields_for :items do |i| %>
    <%= i.input :name, label: "Item Name" %>
  <% end %>
<% end %>

我希望得到 2 个名为“项目名称”的字段,每个 SomeFormItem 添加到 items,但是,我只得到 1,而且它没有以我通常期望的数组格式命名,例如some_form[items][0][name].

有人知道我在这里做错了什么还是我需要手动执行此操作?

【问题讨论】:

    标签: ruby-on-rails ruby simple-form simple-form-for


    【解决方案1】:

    我认为你应该为你的嵌套项声明一个 id 属性,并在将它呈现在表单中之前为其分配一个(整数)值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-09
      • 1970-01-01
      相关资源
      最近更新 更多