使用我的rails应用程序,我正在努力完成下面的图像。
发票应包含多个项。例如,Invoice_1将包含在 invoice_items 容器中:
[{item: Egg, quantity: 3, unit_price: 4}, {item: Stick, quantity: 4, unit_price: 2}]
。
如何制作表格以将 n 商品添加到发票?
或者如何编辑此表单/控制器以创建固定数量的 InvoiceItems 作为开始。稍后我会想到如何创建 Items 并在html中动态创建关联。
class Item < ActiveRecord::Base
has_many :invoice_items
has_many :invoices, through: :invoice_items
end
class Invoice < ActiveRecord::Base
has_many :invoice_items, inverse_of: :invoice
has_many :items, through: :invoice_items
accepts_nested_attributes_for :invoice_items
validates :items, :length => { :minimum => 1 }
end
class InvoiceItem < ActiveRecord::Base
belongs_to :invoice
belongs_to :item
validates_presence_of :invoice
validates_presence_of :item
accepts_nested_attributes_for :item
end
# GET /invoices/new
def new
@invoice = Invoice.new
@invoice.invoice_items.build
end
private:
def invoice_params
#params.fetch(:invoice, {})
params.require(:invoice).permit(
:date,
:seller_id,
:client_id,
invoice_items_attributes: [ item_attributes:
[:name, :quantity, :unit, :unit_price_cents, :unit_price_currency, :price_cents, :price_currency ]
],
invoice_name_attributes: [:number, :month, :year],
)
end
<%= form_for(@invoice) do |invoice_form| %>
<%= invoice_form.fields_for :invoice_items do |invoice_item_form| %>
<%= invoice_item_form.fields_for :item do |item_form| %>
<%= item_form.text_field :name %>
<% end %>
<% end %>
<div class="actions">
<%= invoice_form.submit %>
</div>
<% end %>
答案 0 :(得分:1)
根据我正在阅读的内容,您可能只想专注于制作从发票构建的InvoiceItem记录。您可以使用控制器中新方法中的n.times {invoice.invoice_items.build}等代码构建固定数量(n)的发票项目。
当你想创建动态字段时,有一个名为Cocoon的gem,它允许你动态地将相关记录添加到表单中。
我的建议只是使用您在表单中已经完成的fields_for:invoice_items并省略fields_for:items。而是在invoice_items表单中添加一个select_tag,其中包含您要添加到发票中的所有项目。