大佬教程收集整理的这篇文章主要介绍了安装导轨时出错。 Rails 不起作用,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
嗨,我正在我的 Rails 中创建一个 ec 站点。
我的迁移:(Item) 有:name 和:price。 (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,foreign_key: true
t.integer :quantity,default: 1
t.timestamps
end
end
end
///
Items
class CreateItems < ActiveRecord::Migration[5.2]
def change
create_table :items do |t|
t.references :admin,foreign_key: true
t.string :name,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)
您只提供了迁移文件,所以我的回答将基于一些假设:
So Basket_items is JOIN Table between (Item) and (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
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.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" = ?
Read more 关于 Rails 中的 has_many :through
关联。
以上是大佬教程为你收集整理的安装导轨时出错。 Rails 不起作用全部内容,希望文章能够帮你解决安装导轨时出错。 Rails 不起作用所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。