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ステートメントを評価したかどうかにかかわらず、コードは常にそこを通り抜けているようです)。
ありがとうございます。アイテムが破棄されている場合は、迅速なフォローアップの質問、line_item.saveコマンドは何ですか? (保存するものはないと思われます)。 – Alex
http://apidock.com/rails/ActiveRecord/Transactions/saveから呼び出されるメソッド呼び出しの連鎖に従って、答えを決定することができます。 – Gazler
Gotler - ガズラーに感謝します。 – Alex