Reputation: 316
I encountered an issue today I haven't seen before - I have a custom validation to check if a discount code has already been used in my Order model:
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
In my controller:
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
So it looks like at update_attributes, it runs the validation, fails the validation, creates the error message, and then once it's back at my controller the error message is gone. I'm stumped as to what can be causing that issue.
EDIT:
Here is what current_order is:
In ApplicationController.rb:
def current_order
session[:order_id].present? ? Order.find(session[:order_id]) : Order.new
end
Upvotes: 0
Views: 65
Reputation: 18070
Looks like every time you call current_order it reruns the find method. You can confirm this in the logs, but try not to call that, or at least memoize it. In an instance variable, the same order will be used everytime.
def current_order
@current_order ||= (Order.find_by_id(session[:order_id]) || Order.new)
end
Upvotes: 1