2

チェックアウト バスケットを含む Rails アプリを開発しており、基本的なヘルプが必要です。

一部の製品の価格設定に必要な論理的な議論を統合するのに苦労しています。私がやりたいことは、カートに5つ以上の製品が追加された場合、製品の価格を下げることです.

現在、製品、line_items、カート、および注文のモデルとコントローラーがあり、典型的な関連付けがあります。

メソッドで定義できる簡単なステートメントがあると確信していif and elseifますが、他の人がこれをベストプラクティスとして実装する方法を知りたいですか?

よろしくお願いします。エル

4

1 に答える 1

1

I'm not sure when you're working with a Cart versus an Order. Let's assume you're mostly working in Cart which has a many-to-many relationship to LineItems. At some point, I guess, the Cart becomes an order when the user enters their credit card number.

  1. First I would say that Lineitem should have a discounted field. So LineItem doesn't necessarily store the discounted price; you let the Order or Cart class determine it's actual final price.

  2. Second use and association callback to automatically apply the discount when a line item gets added to the order.

    class Cart
      has_many :line_items, 
          after_add: :calculate_volume_discount,   
          after_remove: :calculate_volume_discount
    
      # When a line item is added or removed determine if current items
      # are entitled to a discount
      def calculate_volume_discount line_item
        current_count = line_items.count
        line_items.each do |li|
          li.discounted = (current_count >= 5)
          li.save
        end  
      end
    end
    
于 2012-10-31T01:19:21.137 に答える