我想用这段代码检索文件中的用户信用卡列表,并将Stripe显示在他的配置文件(/user/:id)上
@stripe_cards = Stripe::Customer.retreive(self.stripe_customer_id).cards.all
问题是,我不太清楚(就Rails最佳实践而言)它适合哪里。我的第一个想法是把它放在用户控制器的显示方法中,因为它不是真正的业务逻辑,也不适合于模型。我也看过助手方法,但(据我理解),它们似乎在玩HTML时被严格使用。
你们中的任何一个Rails专家能参与进来吗?
谢谢!弗朗西斯
发布于 2013-12-03 20:38:49
问得好。每当您在rails中看到实例变量(从@
开始)时,它通常是一个视图/控制器代码。
@stripe_cards = Stripe::Customer.retreive(self.stripe_customer_id).cards.all
然而,看看它的尾部
Stripe::Customer.retreive(self.stripe_customer_id).cards.all
这可能更适合于模型,在这个模型中,您可以重用同一行的,但是具有添加错误处理和可预测行为的安全性。例如
# user.rb
def stripe_customer_cards
Stripe::Customer.retreive(self.stripe_customer_id).cards.all
rescue Stripe::InvalidRequestError
false # You could use this to render some information in your views, without breaking your app.
end
还请注意self
的使用。这通常意味着使用Rails模型,因为在控制器中调用self
实际上是指控制器,使其几乎毫无价值,除非您真正知道自己在做什么。
编辑
若要呈现错误消息,只需使用alert
选项编写一个重定向或呈现调用即可。
if @stripe_cards = current_user.stripe_customer_cards
# Your being paid, sweet!
else
# Render alert info :(
render 'my_view', alert: 'This is an alert'
redirect_to other_path, alert: 'Another alert'
end
我也想指出一点,你不应该仅仅因为你能处理错误而去处理错误。不要处理您不期望的错误。如果您处理错误,则不希望它发生。
发布于 2013-12-03 21:52:32
我建议在User
模型中添加一个虚拟属性:
# app/models/user.rb
def cards
Stripe::Customer.retrieve(stripe_customer_id).cards.all # note the spelling of `retrieve`
end
然后,您将能够以下列方式访问所有用户卡:
user = User.first
#=> #<User id:1>
user.cards
#=> [Array of all cards]
https://stackoverflow.com/questions/20366236
复制相似问题