代码之家  ›  专栏  ›  技术社区  ›  dgreen22

Rails模型中项目的总和-无类错误

  •  0
  • dgreen22  · 技术社区  · 6 年前

    我正在尝试将产品模型和服务模型中的值添加到订单模型中。我将在下面发布模型,这样关系就清晰了。我尝试过多种选择,但本质上,如果我添加了一个产品项目而没有服务项目,它就会崩溃,反之亦然。这里的信息: 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
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Josh Brody    6 年前

    nil optional: true

    present? total line_items

    class LineItem < ApplicationRecord
      def total_as_product
        return 0 unless product.present? 
        product.price.to_i * self.quantity
      end 
    
      def total_as_service
        return 0 unless service.present?
        service.price.to_i * self.quantity
      end 
    end 
    

    def total_product_items
      self.line_items.collect { |item| item.total_as_product }.sum
    end 
    
    def total_service_items
      self.line_items.collect { |item| item.total_as_service }.sum
    end 
    

    eager-loading your associations

    before_update before_save