Last Updated: February 25, 2016
·
1.534K
· bengy

Assigning Charges To Resources With Stripe Checkout

Stripe's Checkout feature creates a charge token client side, and then (Assuming you followed the same naming syntax in Stripe's rails tutorial) it passes that token to the 'ChargesController.'

Stripe's checkout doesn't require any interaction with your database so there isn't a Charges model. This also explains why the embedded ruby for the Stripe JS checkout from the example uses the form tag method instead of the form for method.

Without a model you can't easily pass parameters from another controller through to the charges controller. There are some convoluted workarounds you can do using helpers, sessions, or methods in the 'ApplicationController,' but these solutions aren't very succinct.

You can achieve this very neatly using nested routes. In your routes.rb file nest the charges resource inside the resource that you want to inherit variables from.

# resourcename routes
 resources :resourcename do |resourcename|
      # Charges routes
      resources :charges
 end

Next, you need to update your charges path reference(s).

<%= form_tag resourcename_charges_path(@resourcename) do %>
    <script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
        data-key="<%= Rails.configuration.stripe[:publishable_key] %>"
    ></script>
<% end %>

Finally, update your 'ChargesController' by adding this code to each method where you call on the @resourcename variable.

@resourcename = Resourcename.find(params[:resourcename_id])