Rails最佳实践 - 控制器或模型?

时间:2013-12-04 03:27:53

标签: ruby-on-rails stripe-payments

我想使用这段代码检索用户的条目信用卡列表,使用Stripe在他的个人资料上显示(/ users /:id)

@stripe_cards = Stripe::Customer.retreive(self.stripe_customer_id).cards.all

事情是,我不确定它适合的位置(就Rails最佳实践而言)。我的第一个尝试是把它放在用户控制器的show方法中,因为它不是真正的业务逻辑而且不适合模型。我也看过辅助方法,但它们似乎(根据我的理解)在使用HTML时严格使用。

你们中的任何一位Rails专家都可以加入吗?

谢谢! 弗朗西斯

2 个答案:

答案 0 :(得分:4)

好问题。每当你在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

我还想提一点,你不应该因为你可以处理错误。 不要处理您不期望的错误。如果您处理错误,则不会发生错误

  • 混淆用户
  • 让代码中的错误更难修复
  • 夸大识别错误之前的时间

答案 1 :(得分:2)

我建议您在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]