Question

I have Stripe and PayPal setup on the subscription model. I need help understanding how to create the association between the subscription and the users model.

Any help with this would be greatly appreciated.

Subscription model:

    belongs_to :plan
      validates_presence_of :plan_id
      validates_presence_of :email

      attr_accessor :stripe_card_token, :paypal_payment_token

      def save_with_payment
        if valid?
          if paypal_payment_token.present?
            save_with_paypal_payment
          else
            save_with_stripe_payment
          end
        end
      end

      def paypal
        PaypalPayment.new(self)
      end

      def save_with_paypal_payment
        response = paypal.make_recurring
        self.paypal_recurring_profile_token = response.profile_id
        save!
      end

      def save_with_stripe_payment
        customer = Stripe::Customer.create(description: email, plan: plan_id, card: stripe_card_token)
        self.stripe_customer_token = customer.id
        save!
      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

      def payment_provided?
        stripe_card_token.present? || paypal_payment_token.present?
      end

  def cancel_recurring
     response = ppr.cancel_subscription(at_date_end: true)
     self.current_date_end_at = Time.at(response.current_date_end)
     self.plan_id = plan.id
     self.status = "canceled"
     return self.save
   end
    end
Was it helpful?

Solution

I would probably have a has_one -> belongs_to between users and subscriptions. The Subscription has many attributes that can change a lot over time and when designing anything one of the first questions you should ask is, "what is going to change over time?"

You could then make a subscribed? method on the user for syntactic sugar

class User < ActiveRecord::Base
  has_one :subscription

  def subscribed?
    subscription.present?
  end
end

class Subscription < ActiveRecord::Base
  belongs_to :user
end

You'll want to have a column in your subscription table for user_id so you can use the association properly.

In addition, in the migration, you can add this column by using belongs_to (if you're on a newer version of Rails:

create_table :subscriptions do |t|
  t.belongs_to :user
  t.string :account_id
  t.timestamps
end

If you have everything set up right, then this should work in the rails console:

User.first.subscription # => Subscription<>
Subscription.first.user # => User <>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top