Ruby on rails 安装rails时出错。轨道不';行不通
嗨,我正在我的rails中创建一个ec站点 我的迁移:(项目)有:name和:price。(购物篮商品)有:商品标识(fk)、:购物篮标识(fk)和:数量 系统用户将向他们的购物篮中添加一些物品。所以Basket_items是(Item)和(Basket)之间的连接表,如下所示 我想做的是: 获取商品的价格,并从用户选择的篮子商品中获取数量。然后我想创建@total\u price=项目价格*项目数量。 有人能帮我创建@total_price吗 这是我的一段试用代码,但在rails控制台上不起作用Ruby on rails 安装rails时出错。轨道不';行不通,ruby-on-rails,ruby,Ruby On Rails,Ruby,嗨,我正在我的rails中创建一个ec站点 我的迁移:(项目)有:name和:price。(购物篮商品)有:商品标识(fk)、:购物篮标识(fk)和:数量 系统用户将向他们的购物篮中添加一些物品。所以Basket_items是(Item)和(Basket)之间的连接表,如下所示 我想做的是: 获取商品的价格,并从用户选择的篮子商品中获取数量。然后我想创建@total\u price=项目价格*项目数量。 有人能帮我创建@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
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)
您只提供了迁移文件,因此我的回答将基于以下假设:
所以Basket\u items是(Item)和(Basket)之间的联接表。
-考虑到Basket和items的逻辑,这意味着通过BasketItem,Item和Basket之间存在多对多关系,如下所示:#basket.rb
类篮<应用程序记录
属于:用户
有很多:篮子物品
有多个:项目,通过::篮子项目
结束
#项目1.rb
类项<应用程序记录
有很多:篮子和物品
有很多:篮子,通过::篮子
结束
#basket_item.rb
class BasketItem
prepare\u basket
是做什么的,只是确保您从这个方法中得到了正确的basket@total_price=basket.items.sum('items.price*basket_items.quantity'))
或者在模型中定义它:
#basket.rb
类篮<应用程序记录
属于:用户
有很多:篮子物品
有多个:项目,通过::篮子项目
def总价
项目.总额('items.price*basket\u items.quantity')
结束
结束
basket=get_user_basket#找到你要使用的basket
@总价=篮子。总价
在console中创建一些basket、items和basket_项(如果使用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" = ?
about
有很多:通过Rails中的关联。假设您有一个装满篮子项目的篮子。您可以使用basket.basket\u items.map{r | r.quantity*r.item.price}.reduce(0,:+)
(如果出现错误,未测试可能需要调整)问题标题与内容不匹配。
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" = ?