I want the sign up form on my site to have a field that takes the sum of a math equation and use rails validation to validate it. Whats the best way to do it?
我希望我的网站上的注册表单有一个字段,它取一个数学方程的总和,并使用rails验证来验证它。什么是最好的方法呢?
i.e
What is 6 + 9 ? [ 8 ]
什么是6 + 9? [8]
Error Message : You have entered the wrong number
错误消息:您输入的号码错误
1 个解决方案
#1
Override the validate
method in your model class. Remember that the model object you create for the new
action is a different instance than the one created for the create
action, so you'll need to save the random seed or the math expression somewhere in your form so that you can recreate it during validation.
覆盖模型类中的validate方法。请记住,为新操作创建的模型对象与为create操作创建的模型对象不同,因此您需要在表单中的某处保存随机种子或数学表达式,以便在验证期间重新创建它。
Then, something along the lines of:
然后,有些东西:
def validate
unless math_equation_answered?
errors.add("math_answer", "is incorrect")
end
end
The implementation of math_equation_answered?
is up to you, and math_answer
should be changed to whatever model field you use for the user's answer.
math_equation_answered的实现?由您决定,math_answer应该更改为您用于用户答案的任何模型字段。
#1
Override the validate
method in your model class. Remember that the model object you create for the new
action is a different instance than the one created for the create
action, so you'll need to save the random seed or the math expression somewhere in your form so that you can recreate it during validation.
覆盖模型类中的validate方法。请记住,为新操作创建的模型对象与为create操作创建的模型对象不同,因此您需要在表单中的某处保存随机种子或数学表达式,以便在验证期间重新创建它。
Then, something along the lines of:
然后,有些东西:
def validate
unless math_equation_answered?
errors.add("math_answer", "is incorrect")
end
end
The implementation of math_equation_answered?
is up to you, and math_answer
should be changed to whatever model field you use for the user's answer.
math_equation_answered的实现?由您决定,math_answer应该更改为您用于用户答案的任何模型字段。