代码之家  ›  专栏  ›  技术社区  ›  xps15z

将订阅模型与用户模型关联

  •  1
  • xps15z  · 技术社区  · 11 年前

    我在订阅模式上设置了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
    
    1 回复  |  直到 11 年前
        1
  •  2
  •   Zoran    8 年前

    我可能会有一个has_one->属于用户和订阅之间。订阅有许多属性,随着时间的推移会发生很大变化,在设计任何东西时,您应该首先问的一个问题是:“随着时间的流逝,会发生什么变化?”

    然后你可以 subscribed? 句法糖的用户方法

    class User < ActiveRecord::Base
      has_one :subscription
    
      def subscribed?
        subscription.present?
      end
    end
    
    class Subscription < ActiveRecord::Base
      belongs_to :user
    end
    

    您希望在订阅表中有一列 user_id 这样您就可以正确使用关联。

    此外,在迁移中,可以使用 belongs_to (如果您使用的是较新版本的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 <>