ruby-on-rails - 创建订单后如何使用 invoice_rows 设置发票?
问题描述
我试图弄清楚如何在保存预订后自动设置invoice
with 。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
解决方案
正如评论中所建议的,我使用@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
推荐阅读
- installation - 在 Windows 容器中安装 Microsft Edge
- oracle - 如何通过 Oracle 表知道应用程序名称
- reinforcement-learning - 在任意初始状态下启动 OpenAI gym
- c# - 我的精灵只有在靠近玩家时才会翻转
- android - Android - 如何从软输入键盘中删除建议行
- html - 使悬停功能与移动设备兼容
- python - 导入 Fernet 对象和导入完整模块有什么区别?
- relational-algebra - 使用关系代数找到元素的正确子集
- java - Java 类型转换和变量类型赋值
- reactjs - ReactJs/Gatsby 与 Clarifai 处理 Netlify 错误