嵌套表单:如何使用fields_for正确访问某个实例

时间:2017-12-25 07:53:51

标签: ruby-on-rails nested-forms

我有订单,它总是有两个地址:发票地址送货地址。在视图中,我有一个表单,您可以在其中输入两个地址。从我的控制器传递实例 @order ,已经构建了两个地址的子实例。

从我的OrdersConntroller中提取:

def new
  @order = Order.new(orderCreationDate: Time.now)
  2.times{ @order.addresses.build }
end

在视图中,我如何才能访问第一个@ order.addresses,然后在其他地方访问第二个@ order.addresses?

到目前为止我已尝试过:

<%= form_for @order do |f| %>
...
  <%= f.fields_for :addresses do |ff| %>
   <%= ff.text_field :firstName %> 
  ...
  <% end %>
<% end %>

但是HTML结果如下(名称和id不正确)。

<input type="text" name="order[a][firstName]" id="order_a_firstName">      

从我的订单模型中提取:

has_many :addresses, foreign_key: "orderID"
accepts_nested_attributes_for :addresses, allow_destroy: true

支持Thx。

1 个答案:

答案 0 :(得分:1)

您需要创建两个模型1)InvoiceAddress和2)ShippingAddress

class InvoiceAddress < ActiveRecord::Base
   self.table_name = :address
end

class ShippingAddress < ActiveRecord::Base
   self.table_name = :address
end

并按顺序模型使用关联

has_one :invoice_address
has_one :shipping_address

和orders_controller.rb

def new
  @order = Order.new(orderCreationDate: Time.now)
  @invoice_address = @order.build_invoice_address
  @shipping_address = @order.build_shipping_address
end

表格将

<%= form_for @order do |f| %>
   ...
   <%= f.fields_for :invoice_address, @invoice_address  do |ff| %>
      <%= ff.text_field :firstName %> 
      ...
   <% end %>
   <%= f.fields_for :shipping_address, @shipping_address  do |ff| %>
      <%= ff.text_field :firstName %> 
      ...
   <% end %>
<% end %>