我有以下内容:
after_action :prevent_order_create, :only => [:update, :create]
...
private
def prevent_order_create
@order = Order.find(params[:id]) #line 270
@listing = Order.find_by(params[:listing_id])
@order_seller = @order.where(order_status: [1]).where(:seller)
if @order_seller.count >= 0
@listing.update_column(:listing_status, 3)
end
end
目标是限制任何一位卖家可以打开的订单数量。
使用此代码时,出现以下错误:
ActiveRecord::RecordNotFound (Couldn't find Order without an ID):
app/controllers/orders_controller.rb:270:in `prevent_order_create'
已创建订单,但无论出于何种原因发生此问题。在下单没有问题之后,是否应该检查该方法?
使用0
进行测试。
编辑:
我做到了:
def prevent_order_create
@order_seller = Order.where(order_status: [1]).where(listing_id: Listing.ids)
if @order_seller.count >= 10
@listing.update_column(:listing_status, 3)
end
end
似乎可以立即使用。将更新。
答案 0 :(得分:1)
您描述的一切都符合预期。
在执行完一个动作后执行一个after动作,因此该记录在异常发生时已经保存到您的数据库中。
由于params[:id]
是nil
引起了异常,这对于创建操作是有意义的。
OP说:
我想在创建和更新后找到与
:listing_id
相匹配且与[1]的order_status
相匹配的订单,然后计算这些记录。如果计数> = 1000,则要更改列表的listing_status
我认为我将在after_save
模型中的Order
中进行操作。根据您的最新修改,例如:
scope :status_one, -> { where order_status: 1 } # I'm guessing this should be 1 not [1] as you keep putting
after_save :update_listing
def update_listing
if listing.orders.status_one.count >= 10
listing.update! listing_status: 3
end
end
基本上就是说,如果关联的清单有10个或更多的order_status = 1的关联订单,则将其状态设置为3。