I had a quick question while going though the Agile Web Development with Rails book that I wasn’t able to find the answer to while looking through the website. I have two methods:
This method is in my controller:
def decrement
@line_item = LineItem.find(params[:id])
@line_item = @line_item.decrement_quantity(@line_item.id)
respond_to do |format|
if @line_item.save
format.html { redirect_to store_url }
format.json { render json: @line_item, status: :created, location: @line_item }
else
format.html { render action: "new" }
format.json { render json: @line_item.errors, status: :unprocessable_entity }
end
end
And this is in the corresponding model:
def decrement_quantity(line_item_id)
current_item = LineItem.find_by_id(line_item_id)
if current_item.quantity > 1
current_item.quantity -= 1
else
current_item.destroy
end
current_item
end
I know this is not the most efficient code, but my question is if current_item gets destroyed in the model method, then what is that method returning? (nil?) Is current_item as a variable still existent, just the database object has been destroyed? How can the decrement method in the controller save an object that has been destroyed? (I put a logger.debut statement in the controller method’s if statement, and it seems that the code always goes through there whether or not the model method evaluated the if or else statement).
The model still exists for the duration of the call, but it has been removed from the database and if you call
current_item.destroyed?then it will return true.Even if the item has been destroyed, the
savemethod returns true.Here is some terminal output that hopefully helps.