2013-03-14 51 views
0

我有一個用戶模型,CreditCard模型,然後是付款模型的Rails 3程序。用戶has_many CreditCards,以及CreditCard has_many支付。Rails 3 - 控制器中的關聯驗證?

在我的申請中,當用戶進行新的支付時,他從他的卡片列表中選擇他想用來支付的信用卡。我想在代碼中添加額外的驗證,以確保提交給Payment.create()函數的credit_card_id實際上是當前用戶擁有的。

感覺這樣的驗證將不得不在控制器中發生,對吧?或者是否有處理這種情況的最佳做法?

回答

0

你肯定會想要做這種驗證你的模型。它通常被認爲是保持你的controllers skinny和胖模型的Rails最佳實踐。

假設付款屬於用戶,並且付款屬於信用卡(我假設這是因爲您的付款中有credit_card_id字段),您可以這樣做。

Class Payment < ActiveRecord::Base  
    belongs_to :user 
    belongs_to :credit_card 

    validate :credit_card_belongs_to_user 

    def credit_card_belongs_to_user 
    errors.add(:credit_card, 'does not belong to you') unless user == credit_card.user 
    end 
end 
3

添加驗證付款。支付最有可能關聯到用戶通過belongs_to所以我建議增加以下驗證

# payment.rb 
belongs_to :user 
validate :validates_credit_card_belongs_to_user 

private 

def validates_credit_card_belongs_to_user 
    unless user.credit_card.where(id: credit_card_id).exists? 
    errors.add(:credit_card_id, 'is not owned by this user') 
    end 
end 
0

,你還可以在PaymentsController獲取信用卡這樣的[在之前過濾器]

@credit_card = current_user.credit_cards.find(PARAMS [:credit_card_id])

然後

@payment = @ credit_card.payments.build(PARAMS [:付款])

這樣,你一定會認爲它是由CREDIT_CARD擁有CURRENT_USER 。