Rails / SimpleForm:如何为两组嵌套属性指定参数?

时间:2019-08-12 19:21:13

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

我有一个模型,该模型与另一个模型有两个不同的关联:

class Order < ApplicationRecord
  belongs_to :customer, required: true
  belongs_to :delivery_address,
             class_name: 'Address',
             foreign_key: :delivery_address_id
  belongs_to :collection_address,
             class_name: 'Address',
             foreign_key: :collection_address_id

  accepts_nested_attributes_for :collection_address, :delivery_address
end

它接受嵌套的属性:

<h1>Edit order</h1>
<%= simple_form_for @order, url: order_path do |form| %>
    <strong>Collection address</strong>
    <%= form.simple_fields_for @collection_address, as: :collection_address do |collection_address_form| %>
      <%= collection_address_form.input :address1 %>
        ...
    <% end %>
    <br>
    <strong>Re-delivery address</strong>
    <%= form.simple_fields_for @redelivery_address, as: :delivery_address do |delivery_address_form| %>
      <%= delivery_address_form.input :address1 %>
      ...
    <% end %>
  <%= form.button :submit %>
<% end %>

我想接收两组参数:params[:collection_addressparams[:delivery_address

但是,当表单提交时,控制器不会同时接收两个地址的参数。相反,它在键params[:address]下收到一组。

我知道form_for接受:as选项。我在上面用过。我希望得到params[:delivery_address]params[:collection_address],但我只会得到params[:address]

这是应该与“简单表单”一起使用还是我需要做一些不同的事情?我的代码有什么问题阻止了两个参数集的创建?

1 个答案:

答案 0 :(得分:0)

您可以指定

<%= delivery_address_form.input :address1, input_html: {name:'delivery_address[address1]' } %>

对于每个字段。我知道这有点脏,但是……要完成工作