我有一个模型叫PaymentNotifications
. 只有在 Paypal 有效时,它才用于记录付款。我需要检查他们给我的交易代码是否与我在发布表格后从他们那里得到的交易代码相同。
所有这些都有效。然后我要做的是根据以下一些标准检查它是否有效:
在控制器中,我有以下内容:
tx = params[:tx]
paypal_data = get_data_from_paypal(tx)
res_hash = create_hash(paypal_data)
@payment_notification = PaymentNotification.new(:params => res_hash, :quotation_id => res_hash['invoice'],:status => res_hash["payment_status"],:transaction_id => res_hash["txn_id"])
if paypal_data["SUCCESS"] && @payment_notification.is_valid?(tx) && @payment_notification.save
redirect_to thankyou_path(:id => @payment_notification.quotation_id)
else
render '/pages/error'
end
然后在模型中我运行我的方法is_valid?
validates :params, :quotation_id, :status, :transaction_id, presence: true
validates :transaction_id, :uniqueness => true
def is_valid?(tx)
amount_paid_valid?(params["payment_gross"]) && transaction_valid?(tx) && is_quotation_unpaid?
end
def transaction_valid?(tx)
if tx != transaction_id
errors.add(:transaction_id, "This transaction is not valid")
return false
else
return true
end
end
def is_quotation_unpaid?
if quotation.unpaid?
return true
else
errors.add(:quotation_paid, "This quotation has already been paid.")
return false
end
end
def amount_paid_valid?(amount_paid)
if amount_paid.to_i == quotation.price.to_i
return true
else
errors.add(:amount_paid, "The amount paid does not match the price quoted.")
return false
end
end
注意::amount_paid
并且:quotation_paid
不是属性。它们只是错误消息的键。
我想我在这里错过了这艘船,因为必须有一种方法可以通过 Rails 内置的验证来做到这一点,但我对 Rails 还不是很擅长。有人可以帮我重构它,以便更容易维护并符合最佳实践吗?