Created
July 28, 2025 18:43
-
-
Save maccelf/35356ea5828730d321cb9422eab6338a to your computer and use it in GitHub Desktop.
Orders controller
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class OrdersController < ApplicationController | |
| # This action processes the payment for a given order. | |
| def process_payment | |
| @order = Order.find(params[:id]) | |
| # Attempt to charge the user via a payment gateway | |
| payment_successful = PaymentGateway.charge( | |
| amount: @order.total_amount, | |
| card_token: params[:payment_details][:card_token] | |
| ) | |
| if payment_successful | |
| # Update the order status and record the payment | |
| @order.update(status: 'paid') | |
| Payment.create(order_id: @order.id, amount: @order.total_amount, status: 'success') | |
| # Update the stock for each product in the order | |
| @order.line_items.each do |item| | |
| product = item.product | |
| new_stock = product.stock - item.quantity | |
| product.update(stock: new_stock) | |
| end | |
| # Send a confirmation email | |
| OrderMailer.confirmation_email(@order).deliver_now | |
| # Flag related products for a promotion | |
| Product.where("category_id = #{@order.category_id} AND promotional = true").update_all(last_ordered_at: Time.now) | |
| flash[:notice] = 'Thank you! Your order has been processed.' | |
| redirect_to order_path(@order) | |
| else | |
| flash[:alert] = 'There was a problem with your payment.' | |
| render :show, status: :unprocessable_entity | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment