我正在开发一个Rails应用程序,允许使用Stripe进行高级会员注册,并且正如人们所预料的那样,可以取消该会员资格。要取消成员资格,用户单击一个按钮,触发Promembers_controller.rb中的destroy
操作。在destroy
内部,调用了一个实例方法cancel_subscription
,它与一些JavaScript一起通过调用customer.cancel_subscription
来处理使用Stripe取消成员资格。检查我的条带测试记录,会员资格被取消,但是,好像方法cancel_subscription
返回false,因为这个不成功的重定向一直在运行
redirect_to (:back), :notice => "Not successful. Please try again or contact us."
以及destroy
操作中的其余代码(即@promember.cancel_subscription(id)
之后的代码未运行。
问题:(这是借来的代码)。 cancel_subscription方法是否总是会返回救援结束时的false
(即使没有进行救援),这就是为什么销毁行动的else
子句中的重定向是总是被叫?什么是实现我想要做的更好的方法?
Promembers_controller.rb
def destroy
id = current_user.customer_id
@promember = current_user.promember
if @promember.cancel_subscription(id)
session[:pro] = nil
current_user.customer_id = nil #is not getting run
current_user.promember.delete #is not getting run
current_user.last_four_digits = nil #is not getting run
current_user.save
redirect_to lawyer_profile_path(current_user), :notice => "Premium membership has been cancelled."
else
redirect_to (:back), :notice => "Not successful. Please try again or contact us."
end
end
Promember.rb
def cancel_subscription(customer_id)
unless customer_id.nil?
customer = Stripe::Customer.retrieve(customer_id)
unless customer.nil? or customer.respond_to?('deleted')
if customer.subscription.status == 'active'
customer.cancel_subscription
user.remove_role :pro
if user.practices.size > 1
user.practices.delete(user.practices[1])
end
end
end
end
rescue Stripe::StripeError => e
logger.error "Stripe Error: " + e.message
errors.add :base, "Unable to cancel your subscription. #{e.message}."
false
end
答案 0 :(得分:-1)
false
末尾的cancel_subscription
会导致隐式返回。基本上,在Ruby中,如果不存在return语句,则方法将返回最终语句求值的内容。在这种情况下,它等同于return false
。您可以尝试在这样的适当位置添加return true
,因为您希望在删除成功时返回true。
def cancel_subscription(customer_id)
unless customer_id.nil?
customer = Stripe::Customer.retrieve(customer_id)
unless customer.nil? or customer.respond_to?('deleted')
if customer.subscription.status == 'active'
customer.cancel_subscription
user.remove_role :pro
if user.practices.size > 1
user.practices.delete(user.practices[1])
return true
end
end
end
end
rescue Stripe::StripeError => e
logger.error "Stripe Error: " + e.message
errors.add :base, "Unable to cancel your subscription. #{e.message}."
false
end