0
我在通過Rails進行敏捷Web開發時遇到了一個快速問題,我無法通過網站查找答案。我有兩種方法:Rails數據庫調用(.save/.destroy)
此方法在我的控制器:
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
而且這是在相應的模型:
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
我知道這是不是最有效的代碼,但我問題是如果current_item在模型方法中被銷燬,那麼該方法返回什麼? (nil?)current_item是否仍然存在,只是數據庫對象已經被銷燬?控制器中的遞減方法如何保存已銷燬的對象? (我在控制器方法的if語句中放置了一個logger.debut語句,並且無論模型方法是否評估if或else語句,代碼似乎總是經過此處)。
非常感謝你 - 如果物品已被銷燬,那麼什麼(如果有的話)line_item.save命令正在做什麼的快速後續問題? (似乎沒有什麼可以保存的)。 – Alex 2012-04-28 17:04:28
您可以按照從http://apidock.com/rails/ActiveRecord/Transactions/save開始的方法調用鏈來確定答案。 – Gazler 2012-04-28 17:17:59
明白了 - 非常感謝您的幫助Gazler。 – Alex 2012-04-28 21:20:19