首页 > 解决方案 > 安装导轨时出错。导轨不起作用

问题描述

嗨,我在 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-railsruby

解决方案


您只提供了迁移文件,所以我的回答将基于一些假设:

  1. So Basket_items is JOIN Table between (Item) and (Basket)- 考虑到篮子和物品的逻辑,这意味着您通过 BasketItem 在 Item 和 Basket 之间建立了多对多的关系,如下所示:
# basket.rb
class Basket < ApplicationRecord
  belongs_to :user
  has_many :basket_items
  has_many :items, through: :basket_items
end

#item.rb
class Item < ApplicationRecord
  has_many :baskets_items
  has_many :baskets, through: :baskets_items
end

#basket_item.rb
class BasketItem < ApplicationRecord
  belongs_to :basket
  belongs_to :item
end
  1. 我不确定prepare_basket用户实例做什么,只要确保你从这个方法中得到正确的篮子。

使用此配置,可以通过一个请求计算总价格,如下所示:

@total_price = basket.items.sum('items.price * basket_items.quantity')

或在模型中定义它:

# basket.rb
class Basket < ApplicationRecord
  belongs_to :user
  has_many :basket_items
  has_many :items, through: :basket_items

  def total_price
    items.sum('items.price * basket_items.quantity')
  end
end
basket = get_user_basket # find basket you gonna work with
@total_price = basket.total_price

在控制台中创建一些购物篮、商品和 basket_items(如果您使用 来创建商品,则会自动创建该商品basket.items.create(params))并调查生成的 SQL 查询:

SELECT SUM(items.price * basket_items.quantity) FROM "items" INNER JOIN "basket_items" ON "items"."id" = "basket_items"."item_id" WHERE "basket_items"."basket_id" = ?

阅读有关has_many :throughRails 中关联的更多信息。


推荐阅读