Rails 表单不创建唯一的 id

问题描述 投票:0回答:2

这让我发疯。

我有2个型号,

StockShipment
has_many
Recipients

它还有:

accepts_nested_attributes_for :recipients, reject_if: :all_blank, allow_destroy: true

我有这个部分,应该为具有 unique 的嵌套属性创建新行 子索引

<%= form_with model: @stock_shipment do |form| %>
  <%= form.fields_for(:recipients, Recipient.new, child_index: Time.now.to_i) do |recipient_form| %>
    <%= turbo_stream.append('recipients-list', partial: 'shared/recipient_fields', locals: { form: recipient_form, new_record: true }) %>
  <% end %>
<% end %>

它在表单中创建新行,但每个属性都是相同的:

name="[recipients][phone]"

代替:

name="[recipients][12234324][phone]"

这只会创建 1 条记录,而不是分别创建各种记录。

请问有人可以帮忙吗?

我正在使用 Rails 7。

谢谢你。

ruby-on-rails nested-attributes ruby-on-rails-7
2个回答
0
投票

自从我玩这个以来已经有一段时间了,但我相当确定你需要传递一个proc/lambda(响应

.call
的东西),例如:
-> { Time.now.to_i }


0
投票

@stock_shipment
未设置,因此您生成的表单未链接到模型。实际的
name
属性应如下所示:

# v model                   child_index v (when :recipients is an association)
  stock_shipment[recipients_attributes][12234324][phone]
#    association ^          ^ accepts_nested_attributes

当您将

nil
作为模型传递时,不会发生任何魔法:

# v no model  v no child_index (not an association, you'd use :index in this case)
   [recipients][phone]
#   ^        `- no accepts_nested_attributes
#   `-literal argument for fields_for        

由于您在这里不需要实际的

<form>
标签,因此请使用
fields
帮助器而不是
form_with

<%= fields model: StockShipment.new do |f| %>
  <%= f.fields_for :recipients, Recipient.new, child_index: Time.now.to_i do |ff| %>
    #                          can only click once a second ^ just saying
    <%= turbo_stream.append(
      "recipients-list",
      partial: "shared/recipient_fields",
      locals: {form: ff, new_record: true})
      # maybe unnecessary ^ `form.object.new_record?`
    %>
  <% end %>
<% end %>
© www.soinside.com 2019 - 2024. All rights reserved.