首页 > 解决方案 > 如何将 simple_form 与嵌套的 ActiveModel 对象(不是 ActiveRecord)一起使用?

问题描述

在使用该数据执行工作之前,我正在尝试使用simple_form对象ActiveModel来验证表单数据。该数据不会被持久化到数据库中,因此不使用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到.itemssome_form[items][0][name]

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

标签: ruby-on-railsrubysimple-formsimple-form-for

解决方案


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


推荐阅读