Rails 3. 在表单中留下错误的整数属性值
我有模型“Human”,该模型具有整数属性 :age。
例如,我对此整数属性 :age 使用验证。
当我添加新的“Human”时,其 :age 值错误(例如 "2aaa3"),它会返回错误,但它也被剪切 :age 就像 "2"。但我不想要它。我想保留最后一个错误值“2aaa3”。
所以,问题是“我该怎么做?”
I have model 'Human' and this model has integer attribute :age.
For example, I use validation for this integer attribute :age.
When I add new 'Human' with wrong value of :age (e.g. "2aaa3") it is render me back with error, but it is also cut :age like "2". But I don't want it. I want to leave last wrong value "2aaa3".
So, question is "How can I do it?"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是 Rails 中验证的默认行为。不确定是否还有其他方法可以覆盖它。不过,您可以使用 javascript 进行验证,这比使用 validates_numericality_of 更加注重用户体验。
That is the default behaviour of validation in Rails. Not sure if there are any other ways to override it. You could however do that validation using javascript, which will be much more user experience oriented than using validates_numericality_of.
大家好,对我的问题感兴趣。
我很高兴地说我自己创建了解决方案。
但我对此有几点评论。 ))
首先,解决方案是:
其次,备注是:
1) 该解决方案适用于“Formtastic”和“Simple_form”等宝石。这些 gem 构建了包含在详细 html 中的表单,并为我们提供了使用正则表达式的可能性。
如果您不使用此类宝石,您可以将所有整数属性包装起来,例如,在带有“数字”类的“p”标签中,如下所示,我认为我的解决方案也适用于此:
2)我认为我的解决方案将不适用于多模型形式的嵌套模型的整数字段。 (Ryan Bates 在“Advanced Rails Recipes”中的“Handle Multiple Models in One Form”中描述了此类工作)。
但如果您阅读 Ryan Bates 的文章,您会发现他已经使用了 JavaScript。因此,在表单中使用嵌套模型需要 JavaScript。然后你也可以使用 JavaScript 进行验证(正如 Kunday 所说)。你不会有问题的。 ;)
但是,如果您在表单中有静态数量的嵌套模型并且不使用 JavaScript,那么我认为您可以根据您的需求创建新的特定正则表达式(类似于我创建的正则表达式)。我希望你能处理好这个问题。 ;)
我希望我已经涵盖了您可能遇到此类问题的所有场景,并且我的解决方案将对除我之外的其他人有用。 ;)
Hi everybody who is interested in my question.
I am glad to say I've created solution by myself.
But I have several remarks to that. ))
First, the solution is:
Second, remarks are:
1) the solution works along such gems as 'Formtastic' and 'Simple_form'. These gems build the forms wraped in detailed html and give us possibility to use regex.
If you don't use such gems you can just wrap all your integer attributes, for example, in 'p' tag with 'numeric' class like following and I think my solution will work for this too:
2) I think my solution will not work for integer fields of nested models in multiple-models-form. (Ryan Bates describes such kind of work in "Handle Multiple Models in One Form" from "Advanced Rails Recipes").
But if you read Ryan Bates' article you will see that he already uses JavaScript. So, working with nested models in form you need JavaScript. Then you can use JavaScript for validation too (as Kunday told). And you will not have a problem. ;)
But if you have static number of nested models in form and do not use JavaScript, then I think you can create new particular regex for your needs (similar to the one I created). I hope you will manage with this. ;)
I hope I've covered all scenarios where you can have such problem and my solution will be useful for somebody, besides me. ;)