我正在尝试将产品模型和服务模型中的值添加到订单模型中。我将在下面发布模型,这样关系就清晰了。我尝试过多种选择,但本质上,如果我添加了一个产品项目而没有服务项目,它就会崩溃,反之亦然。这里的信息:
NoMethodError (undefined method `price' for nil:NilClass):
to_i
here
class Order < ApplicationRecord
has_many :line_items
before_save :update_total
before_update :update_total
belongs_to :user, optional: true
def total_service_items
self.line_items.collect { |item| item.service.price.to_i * item.quantity }.sum
end
def total_product_items
self.line_items.collect { |item| item.product.price.to_i * item.quantity }.sum
end
def calculate_total
total_service_items + total_product_items
end
def update_total
self.total_price = calculate_total
end
end
class LineItem < ApplicationRecord
belongs_to :order, optional: true
belongs_to :product, optional: true
belongs_to :service, optional: true
end
class Service < ApplicationRecord
has_many :line_items
end
class Product < ApplicationRecord
has_many :line_items
end
Create
class LineItemsController < ApplicationController
def create
@order = current_order
@item = @order.line_items.new(item_params)
@order.save
end
def item_params
params.require(:line_item).permit(:quantity, :service_id, :product_id, :unit_price, :order_id)
end
end