2012-04-27 9 views
0

Agile Web Development with Railsの本を読んでいるうちに、私はウェブサイトを見ている間に答えを見つけることができませんでした。私の二つの方法があります: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

+0

http://apidock.com/rails/ActiveRecord/Transactions/saveから呼び出されるメソッド呼び出しの連鎖に従って、答えを決定することができます。 – Gazler

+0

Gotler - ガズラーに感謝します。 – Alex

関連する問題