为每个新实例实例化(刷新)的类变量



我有两个类Categoryorder_item,其中order_item属于类别。

每当在实例变量中检测到新类别时,我想将唯一的"类别"项添加到类变量中,该类变量是"类别"的数组,由数组类变量@@categoriesList表示。

这就是我尝试过的。

class OrderItemsController < ApplicationController
@@categoriesList = []
def create
@order_item = OrderItem.new(order_item_params)
if @order_item.save
@total = @order_item.order.total
@orderItemCategory = @order_item.category
if @orderItemCategory.set?
if !(@@categoriesList.include? @orderItemCategory)
@total += @orderItemCategory.price
@@categoriesList.push(@orderItemCategory)
end
........
........
end

代码说明:

如果已经考虑了属于同一类别价格的上一个order_item的价格,我不希望考虑order_item的下一个实例的价格。

例如:鸡蛋和牛奶都属于组合-1。因此,我只想考虑一次组合-1的价格,而不是每个订单项的价格,即鸡蛋和牛奶,这将使总量翻倍。

我尝试了什么:

在考虑了订单项的价格后,我推送了它的类别名称。当创建下一个order_item时,我在当前@@categoriesList类变量中检查该order_item的类别价格是否已经记录。

问题:在每个实例中,当我检查类变量@@categoriesList时,它都会返回一个空数组列表,并且不会显示以前推送到该数组的记录。

我想要一个类似java中的静态变量,其中类的每个实例都共享同一个变量,而不需要为每个实例刷新变量中的数据。

您不太想要类变量,因为它们不是线程安全的,或者实际上在请求之间是持久的,这几乎适用于任何编程语言。每次重新加载代码时,类变量都会被重置。

你想做的事情可以通过正确地建模域来完成。在结账系统的情况下,它已经做了十亿次了,常见的模式是:

class Order < ApplicationRecord
has_many :line_items
has_many :products, through: :line_items
end
# rails g model line_item quantity:decimal unit_price:decimal order:belongs_to product:belongs_to
class LineItem < ApplicationRecord
belongs_to :order
belongs_to :product
end
class Product < ApplicationRecord
has_many :line_items
has_many :orders, through: :line_items
end

在代表订单上实际行的行项目表上,您存储项目所属的订单、数量和数量;购买时的单价。要计算订单,您需要对行项目求和:

class LineItem < ApplicationRecord
# ...
def net
quantity * unit_price
end
end
class Order < ApplicationRecord
# ...
def net
line_items.sum(&:net)
end
end

所以你可以直接打电话给order.net,它会给你净额。我不知道你会把类别搞得一团糟,但如果我们通过查看产品来查看这里的价格,我们将无法解释过去的交易,除非价格完全是静态的。

这就是创建行项目的方式:

resources :orders do
resources :line_items
end
class LineItemsController < ApplicationController
before_action :set_order
# GET /orders/1/line_items
def new
@line_item = @order.line_items.new
@products = Product.all
end
# POST /orders/1/line_items
def create
@line_item = @order.line_items.new(line_item_params) do |items|
items.unit_price = li.product.price # stores the price at time of purchase
end
if @line_item.save
redirect_to @order
else
@products = Product.all
render :new
end
end
# ...
private
def line_item_params
params.require(:line_item)
.permit(:quantity, :product_id)
end
def set_order
@order = Order.find(params[:order_id])
end
end
<%= form_with(model: [@order, @line_item], local: true) do |f| %>
<div class="field">
<%= f.label :product_id %>
<%= f.collection_select :product_id, @products, :id, :name %>
</div>
<div class="field">
<%= f.label :quantity %>
<%= f.number_field :quantity %>
</div>
<%= f.submit %>
<% end %>

最新更新