1

我在訂閱模型上設置了Stripe和PayPal。我需要幫助瞭解如何創建訂閱和用戶模型之間的關聯。準用戶模型與用戶模型

任何幫助,這將不勝感激。

訂閱模式:

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 

回答

2

我想可能有一個HAS_ONE - > belongs_to的用戶和訂閱之間。訂閱有許多屬性會隨着時間的推移而發生很大的變化,在設計任何問題時,您應該問的第一個問題是「隨着時間的推移會發生什麼變化?」

然後,您可以做句法糖

class User < ActiveRecord::Base 
    has_one :subscription 

    def subscribed? 
    subscription.present? 
    end 
end 

class Subscription < ActiveRecord::Base 
    belongs_to :user 
end 

你想在你的訂閱表中有一列user_id這樣你就可以正確地使用聯想對用戶subscribed?方法。

此外,在遷移時,您可以通過使用belongs_to添加此列(如果你是on Rails的較新版本:

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

如果一切設置正確的,那麼這應該工作在rails console

User.first.subscription # => Subscription<> 
Subscription.first.user # => User <> 
+1

感謝您迴應我對如何添加模型之間的關係清楚,我需要幫助理解的部分是如何創建的動作例如,當用戶支付和認購表。用令牌和電子郵件更新,如何c我從它更新用戶表來顯示用戶ID 12現在訂閱了計劃1.將訂閱模型設置爲belongs_to是第一小步驟,這就是爲什麼我知道如何執行該部分哈哈。 – xps15z

+0

只要你在belongs_to表中有一個'_id'列,Rails應該爲你填寫它。在你的情況下,添加一個'user_id'到訂閱表。 – WattsInABox

+0

對不起,不得不編輯我的評論。我倒退了。 – WattsInABox