首页 > 解决方案 > 创建订单后如何使用 invoice_rows 设置发票?

问题描述

我试图弄清楚如何在保存预订后自动设置invoicewith 。invoice_rows

尝试

在包括 order_rows 之前,我尝试为订单生成发票:

我尝试@order.invoices.create(order_contact_id: @order.order_contact_id)在创建中保存订单后包含,但这导致了一个空数组:

Order.last.invoice => []

之后我可能应该遍历属于订单的所有产品并将它们作为 invoice_rows 包含在发票中。但不确定如何。

笔记

实际结构更复杂,因此我需要所有表格。

代码

楷模

class Order < ApplicationRecord
  has_many :invoices
  has_many :order_products, dependent: :destroy
end

class OrderProduct < ApplicationRecord
  belongs_to :product
  belongs_to :order
  accepts_nested_attributes_for :product
end

class Product < ApplicationRecord
  has_many :orders, through: :order_products
  has_many :product_prices, dependent: :destroy, inverse_of: :product
  accepts_nested_attributes_for :product_prices, allow_destroy: true
end

class ProductPrice < ApplicationRecord
  belongs_to :product, inverse_of: :product_prices
end

订单控制器

class OrdersController < ApplicationController

  def create
    @order = @shop.orders.new(order_params)
    authorize @order
    if @order.save
      authorize @order
      # @order.invoices.create(order_contact_id: @order.order_contact_id)
      redirect_to new_second_part_shop_order_path(@shop, @order)
    end
  end

private

def order_params
  params.require(:order).permit(:order_contact_id,
  order_products_attributes: [:id, :product_id, :product_quantity, :_destroy,
    products_attributes: [:id, :name, :description]])
  end
end

标签: ruby-on-rails

解决方案


正如评论中所建议的,我使用@order.invoices.create!.

之后我迭代了每个产品并invoice_row为创建的发票创建了一个。

@invoice = @order.invoices.create!(order_contact_id: @order.order_contact_id)
@order.order_products.each do |o_product|
  @invoice.invoice_rows.create!(
     description: o_product.product.name,
     total_price: @reservation.total_product_price(@reservation, o_product)
    )
end


推荐阅读