我有一个Order / LineItem类型的应用程序,它将Order及其关联的行项目插入到数据库中。创建订单后(after_create)然后我调用一个更新Order表中的totals字段的函数。但是,当它运行时,它还会对所有行项目运行更新查询,并且因为paper_trail处于活动状态:update,所以它也会导致插入新版本。问题是,可能有数百个订单项(目前最大的是872个),所以很明显这不是很优化,而且由于纸质跟踪,我们会得到不必要的版本。
我看过:触摸符号,但这似乎只适用于孩子>父母而非父母>子。
有没有办法在更新其父项时停止对订单项触发更新?
以下是精简控制器/模型。
OrdersController:
class OrdersController < ApplicationController
def create
@order = Order.new(order_params)
if @order.save
render :json => @order, :serializer => ::OrderSerializer
end
end
订单型号:
class Order < ActiveRecord::Base
has_paper_trail
belongs_to :customer
has_many :line_items, :dependent => :destroy
after_create :update_total_quantities
accepts_nested_attributes_for :line_items
def update_total_quantities
update_attributes({:total_quantity => calculated_total_quantity})
end
end
LineItem模型:
class LineItem < ActiveRecord::Base
has_paper_trail :on => [:update, :destroy]
belongs_to :order
end
日志中的问题示例:
INSERT INTO "line_items" ("colour", "created_at", "order_id", "price", "product_id", "quantity", "size", "updated_at", "variant_id") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING "id"[0m [["colour", 2], ["created_at", Wed, 08 Jan 2014 11:47:38 UTC +00:00], ["order_id", 1216], ["price", 77.0], ["product_id", 241702], ["quantity", 1], ["size", "18"], ["updated_at", Wed, 08 Jan 2014 11:47:38 UTC+00:00], ["variant_id", "241702_2_18"]
INSERT INTO "line_items" ("colour", "created_at", "order_id", "price", "product_id", "quantity", "size", "updated_at", "variant_id") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING "id" [["colour", 106], ["created_at", Wed, 08 Jan 2014 11:47:38 UTC +00:00], ["order_id", 1216], ["price", 20.0], ["product_id", 2753], ["quantity", 1], ["size", "18"], ["updated_at", Wed, 08 Jan 2014 11:47:38 UTC +00:00], ["variant_id", "2753_106_18"]
UPDATE "orders" SET "total_quantity" = $1, "updated_at" = $2 WHERE "orders"."id" = 1216 [["total_quantity", 878], ["updated_at", Wed, 08 Jan 2014 11:47:40 UTC +00:00]
UPDATE "line_items" SET "created_at" = $1, "updated_at" = $2 WHERE "line_items"."id" = 108533 [["created_at", Wed, 08 Jan 2014 11:47:38 UTC +00:00], ["updated_at", Wed, 08 Jan 2014 11:47:38 UTC +00:00]
UPDATE "line_items" SET "created_at" = $1, "updated_at" = $2 WHERE "line_items"."id" = 108526[0m [["created_at", Wed, 08 Jan 2014 11:47:38 UTC +00:00], ["updated_at", Wed, 08 Jan 2014 11:47:38 UTC +00:00
答案 0 :(得分:0)
我通过更改工作流逻辑来修复此问题。我没有在创建后运行update_total_quantities方法,而是在控制器中运行该方法,因此我更新的代码看起来更像:
OrdersController:
class OrdersController < ApplicationController
def create
@order = Order.new(order_params)
@order.total_quantity = @order.calculated_total_quantity
if @order.save
render :json => @order, :serializer => ::OrderSerializer
end
end
订单型号:
class Order < ActiveRecord::Base
has_paper_trail
belongs_to :customer
has_many :line_items, :dependent => :destroy
accepts_nested_attributes_for :line_items
end