2012-04-27 26 views
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語句,代碼似乎總是經過此處)。

回答

0

模型在調用期間仍然存在,但它已從數據庫中刪除,如果您調用current_item.destroyed?,則它將返回true。

即使該物品已被銷燬,save方法返回true。

這裏有一些終端輸出,希望有所幫助。

1.9.2p290 :001 > current_item = Deck.first 
    Deck Load (0.1ms) SELECT "decks".* FROM "decks" LIMIT 1 
=> #<Deck id: 2, name: "Test Deck 1", description: "This is a te> #snip 
1.9.2p290 :002 > current_item.destroyed? 
=> false 
1.9.2p290 :003 > current_item.destroy 
    (0.2ms) begin transaction 
    SQL (23.1ms) DELETE FROM "decks" WHERE "decks"."id" = ? [["id", 2]] 
    (5.0ms) commit transaction 
=> #<Deck id: 2, name: "Test Deck 1", description: "This is a te> #snip 
1.9.2p290 :004 > current_item.destroyed? 
=> true 
1.9.2p290 :005 > current_item.save 
    (0.2ms) begin transaction 
    (0.1ms) commit transaction 
=> true 
+0

非常感謝你 - 如果物品已被銷燬,那麼什麼(如果有的話)line_item.save命令正在做什麼的快速後續問題? (似乎沒有什麼可以保存的)。 – Alex 2012-04-28 17:04:28

+0

您可以按照從http://apidock.com/rails/ActiveRecord/Transactions/save開始的方法調用鏈來確定答案。 – Gazler 2012-04-28 17:17:59

+0

明白了 - 非常感謝您的幫助Gazler。 – Alex 2012-04-28 21:20:19