簡體   English   中英

如何將simple_form與嵌套的ActiveModel對象(而不是ActiveRecord)一起使用?

[英]How do you use simple_form with nested ActiveModel objects (not ActiveRecord)?

我正在嘗試使用帶有ActiveModel對象的simple_form來驗證表單數據,然后再使用該數據執行工作。 該數據不會持久化到數據庫,因此不使用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 %>

我希望為添加到items每個SomeFormItem獲得2個稱為“項目名稱”的字段,但是,我只能得到1個,而且它的ID也沒有以我通常期望的數組格式命名,例如some_form[items][0][name]

有人知道我在這里做錯了嗎,還是我需要手動執行此操作?

我認為您應該為嵌套項目聲明一個id屬性,並在表單中呈現它之前為其分配一個(整數)值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM