ruby-on-rails - 如何将 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
到.items
some_form[items][0][name]
任何人都知道我在这里做错了什么还是我需要手动执行此操作?
解决方案
我认为您应该为嵌套项目声明一个 id 属性,并在将其呈现在表单中之前为其分配一个(整数)值。
推荐阅读
- facebook-graph-api - 如何以编程方式获取拆分测试的结果?
- javascript - JSX 元素类型“Line”不是 JSX 元素的构造函数
- android - 如何从 initstate 中删除小部件或仅在 initstate 中加载小部件小部件一次?
- google-cloud-platform - RuntimeError:构建自定义图像时出错
- python - 如何在 python 脚本中保护纯文本密码
- jquery - 如何使用 settimeout 在 jquery 中制作 Preloader?
- python - 在 KMeans 算法中获取每个集群中的值的数量
- c# - Outlook VSTO 收件人 MeetingResponseStatus 在接受会议后未更新
- java - 如何在java的I/O流中转换c++的freopen
- rank - 如何计算召回@k