我在订阅模型上设置了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
答案 0 :(得分:2)
我可能有一个has_one - >用户和订阅之间的belongs_to。订阅有许多属性可以随着时间的推移而发生很大变化,在设计任何问题时,您应该问的第一个问题是“随着时间的推移会发生什么变化?”
然后,您可以在用户上为语法糖
创建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 <>