首页 > 解决方案 > 导轨计算(价格*数量)

问题描述

嗨,我在 Rails 中创建了一个 ec 站点。

我的迁移:(项目)有:名称和:价格。(Basket_Item) 有 :item_id(fk)、:basket_id(fk) 和 :quantity。

系统用户会将一些物品添加到他们的购物篮中。所以 Basket_items 是 (Item) 和 (Basket) 之间的 JOIN 表,如下所示。

我想做的事:

从用户选择的 Basket_Items 中获取 Item 的价格和数量。然后我想创建@total_price = item_price * item_quantity。

谁能帮我创建@total_price。

这是我的尝试代码,但它不适用于 Rails 控制台。

Basket_items

class CreateBasketItems < ActiveRecord::Migration[5.2]
  def change
    create_table :basket_items do |t|
      t.references :basket, index: true, null: false, foreign_key: true
      t.references :item, index: true, null: false, foreign_key: true
      t.integer    :quantity, null: false, default: 1
      t.timestamps
    end
  end
end

///

Items

class CreateItems < ActiveRecord::Migration[5.2]
  def change
    create_table :items do |t|
      t.references :admin, index: true, null: false, foreign_key: true
      t.string  :name,  null: false, index: true
      t.integer :price, null: false
      t.text    :message

      t.string  :category, index: true
      t.string  :img 
      t.string  :Video_url
      t.text    :discription
      t.timestamps
    end
  end
end

///

这是我尝试的代码,但它在 Rails 控制台上不起作用。

basket = current_user.prepare_basket
item_ids = basket.basket_items.select(:item_id)
items = basket.items.where(id: item_ids)
items_price = items.select(:price)
items_quantity = basket.basket_items.where(item_id: item_ids).pluck(:quantity)

def self.total(items_price, items_quantity)
  sum(items_price * items_quantity)
end

@total_price = basket.total(items_price, item_quantity)

标签: ruby-on-rails

解决方案


您的代码存在一些问题:您正在尝试调用类class method的a instance。那是行不通的,其次你将数组传递给计算。

basket = current_user.prepare_basket
item_ids = basket.basket_items.select(:item_id)
items = basket.items.where(id: item_ids)
items_price = items.select(:price) # => Array of prices from the items in the basket
items_quantity = basket.basket_items.where(item_id: item_ids).pluck(:quantity) # => Array of quantities from the items in the basket

def self.total(items_price, items_quantity)
  sum(items_price * items_quantity) # => So this line will do: sum(['12,95', '9.99'] * [1, 3])
end

@total_price = basket.total(items_price, item_quantity)

如你所见,那是行不通的。首先,您需要更改方法并删除self.

def total(items_price, items_quantity)
  # ...
end

basket现在你可以在一个对象上调用 total 方法:basket.total(items_price, items_quantity)

total方法内部,您需要遍历每个项目以进行计算并添加所有结果。

def total(items_price, items_quantity)
  total_price = 0
  items_price.each_with_index do |price, index|
    total_price += price * items_quantity[index]
  end
  total_price
end

但是这个解决方案也可能失败,因为您不确定 中的顺序items_price是否与items_quantity. 所以更好的方法是对每个basket_item单独的进行计算。

# Basket model
def total
  total_price = 0
  basket_items.each do |basket_item|
    total_price += basket_item.total_price
  end
  total_price
end

# BasketItem model
def total_price
  quantity * item.price
end

现在你可以这样称呼它:basket.total


推荐阅读