Search code examples
ruby-on-railsactiverecordmodel-associationsstripe-payments

Setting a variable cost in Stripe payment gateway on Rails


I have set up Stripe on Rails, and it is working as anticipated.

I have three models that pertain to an order. A User model, a Course model, and an Order model. They are associated through a has_many association.
When a user purchases a course the order table is updated with the User ID and Course ID.

What I can not figure out is how to NOT hard code the price into the Stripe request and Create Method. The course model has a :cost variable and I would like to set the cost by calling @course.cost. I can't seem to be able to get this to work.

Here is my order model:

class Order < ActiveRecord::Base
    attr_accessible :stripe_card_token, :course_id, :user_id
    attr_accessor :stripe_card_token
  # attr_accessible :title, :body
    belongs_to :course
    belongs_to :user

    def save_with_payment
        @amount = 500
        if valid?
            charge = Stripe::Charge.create(amount: @amount, currency: 'usd', card: stripe_card_token)
            #self.stripe_customer_token = customer.id
            save!
        end
        rescue Stripe::InvalidRequestError => e
        logger.error "Stripe error while creating customer: #{e.message}"
        errors.add :base, "There was a problem with your credit card."
        false
    end
end

And my order Controller:

class OrdersController < ApplicationController

    def new
      @order = Order.new
    end
    def create
      @order = Order.new(params[:order])
        if @order.save_with_payment
           redirect_to @order, :notice => "Thank you for your purchase!  Enjoy your Class!"
           else
           render :new
       end
    end
    end

Solution

  • Figured I would post the answer to this if anyone else comes across it.

    In the order controller:

    def save_with_payment
    
        @amount = self.course.cost
    
        if valid?
            charge = Stripe::Charge.create(amount: @amount, currency: 'usd', card: stripe_card_token)
            #self.stripe_customer_token = customer.id
            save!
        end
    

    The part that I left out was correctly nesting the resource in routes.rb:

    resources :courses do
     resources :orders
    end
    

    And finally in my controller:

    def new
        @course = Course.find(params[:course_id])
        @order = @course.orders.new
    
    end
    

    This works like I need it to, though if anyone else has a better method I am more then open to suggestions! :)