0
我今天遇到一個問題,我還沒有見過 - 我有一個自定義的驗證,以檢查是否有優惠代碼已經在我的訂單模型中使用:Rails的錯誤消息
validate :valid_discount_code
def valid_discount_code
is_valid = false
code = nil
if discount_code.present?
if discount_code.try(:downcase) == 'xyz'
code = 'xyz'
is_valid = true
else
code = Coupon.find_by_coupon_code(discount_code)
is_valid = code.present?
end
if code.nil?
is_valid = false
errors.add(:discount_code, "is not a valid referral code")
elsif (code.present? && Coupon.where(email: email, coupon_code: code).present?)
is_valid = false
errors.add(:discount_code, "has already been used.")
end
puts "------------"
puts errors.full_messages ## successfully 'puts' the correct error message into my console.
puts "------------"
if is_valid
.... do stuff.....
end
end
end
在我的控制器:
if current_order.update_attributes(discount_code: params[:coupon_code].downcase, another_attribute: other_stuff)
....
session[:order_id] = nil
render json: { charged: 'true' }.as_json
else
puts "==============="
puts current_order.id # shows the correct current order ID
puts current_order.errors.full_messages # shows that there are no errors present
puts "==============="
render json: { charged: 'false', errors: current_order.errors.full_messages }.as_json
end
因此,它看起來像在update_attributes,它運行驗證,驗證失敗,創建錯誤消息,然後一旦它回到我的控制器,錯誤消息就消失了。我很難理解可能導致這個問題的原因。
編輯:
這裏是current_order是什麼:
在ApplicationController.rb:
def current_order
session[:order_id].present? ? Order.find(session[:order_id]) : Order.new
end
什麼是'current_order'?這是一個變量或方法嗎?您可以在控制檯中進行測試,並確認它全部在控制器中。 – Swards
@swards current_order是我的應用程序控制器中的一種方法,我將在上面的編輯中包含該方法 – asalgan
另一個潛在的問題是,這個'params [:coupon_code] .downcase'有空嗎? – Swards