簡體   English   中英

Rails最佳實踐-控制器還是模型?

[英]Rails best practices - Controller or model?

我想使用這段代碼來檢索用戶的信用卡列表,其中有Stripe顯示在他的個人資料上(/ users /:id)

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

問題是,我不確定(根據Rails的最佳做法)適合的位置。 我的第一個強項是將其放入User控制器的show方法中,因為它不是真正的業務邏輯,也不適合模型。 我也看過輔助方法,但根據我的理解,它們在使用HTML時似乎嚴格使用。

你們當中的任何Rails專家都可以發出聲音嗎?

謝謝! 弗朗西斯

好問題。 每當您在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

我還想指出,您不應僅僅因為可以就可以處理錯誤。 不要處理意外的錯誤。 如果您處理錯誤,您不會期望

  • 混淆用戶
  • 使代碼中的錯誤難以修復
  • 誇大發現錯誤之前的時間

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM