Reputation: 1481
I have the following:
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
The goal is to limit the amount of orders that can be open for any 1 seller.
When I use this code, I get the following error:
ActiveRecord::RecordNotFound (Couldn't find Order without an ID):
app/controllers/orders_controller.rb:270:in `prevent_order_create'
The order gets created but for whatever reason this issue is happening. Shouldn't the method be getting checked AFTER the order is made without issues?
btw using 0
for testing purposes.
EDIT:
I did:
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
Seems to work for now. Will update.
Upvotes: 0
Views: 43
Reputation: 27961
Everything you describe is as expected.
An after action is run after the action is already executed, so the record has already been persisted to your DB by the time the exception happens.
The exception is caused because params[:id]
is nil
, which makes sense for a create action.
OP said:
I want after create and update... to find any orders with matching
:listing_id
's and withorder_status
's of [1] to then count those records. If the count is >= 1000, to then change the listing_status of the Listing
I think the way I would do this is in an after_save
in the Order
model. Based on your latest edit something like:
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
So that's basically saying that if the associated listing has 10 or more associated orders with order_status=1 then set its status to 3.
Upvotes: 1