I am adding the promo code option for my application. I want to apply validation on the form that will match the entered promo code by the user to the promo code that has been already there in the admin dashboard (Activeadmin is used for admin dashboard).
I have tried a few options but nothing works. Examples that I have tried -
def validate_promo_code
if promo_code.present? and (!promo_code.match(EngineName::PromoCode.promo_code))
errors.add :promo_code, "must be a valid promo code"
end
end
def validate_promo_code
if promo_code.present? and (promo_code != EngineName::PromoCode.where(promo_code: promo_code))
errors.add :promo_code, "must be valid promo code"
return;
end
end
Does anyone has any idea how to achieve this? Please Help!
CodePudding user response:
You have to make your activerecord model aware of the validation using the validate
dsl statement. Does this work?
validate :ensure_valid_promo_code
def ensure_valid_promo_code
if promo_code.present? && (!promo_code.match(EngineName::PromoCode.promo_code))
errors.add :promo_code, "must be a valid promo code"
end
end
CodePudding user response:
In case if someone is still looking for the solution, try this one -
def validate_promo_code
existing_code = EngineName::PromoCode.where(promo_code: promo_code)
if promo_code.present? and !(existing_code.present?)
errors.add :promo_code, "must be valid promo code"
end
end
This solution works for me.