验证成功后的数据转换
我在标准化 UPC 字符串代码时遇到了一些问题,以便我可以将其以相同的格式存储在数据库中。
我正在使用 ean
gem 来检查字符串是否良好(工作正常),但是如果我在验证后抛出一些赋值代码,例如:
validate :upc_check
def upc_check
if !upc.nil?
if !upc.ean?
errors.add(:upc, 'is not a valid UPC.')
else
upc = upc.strip
end
end
end
strip 调用只是一个示例,因为它是一个字符串。我实际上会删除 upc 中的破折号。
上面的代码不能很好地工作,因为它实际上并没有保存它。我查看了触发类似
after_validation :normalize_upc
def normalize_upc
upc = upc.strip
end
.. 的方法,但上面的方法也不起作用。
你们在验证后做什么来验证和转换数据?
I'm having a bit of a problem normalizing a UPC string code so that I can store it in the same format in the database.
I'm using the ean
gem to check if the string is good (which is working fine), but if I throw some assignment code after it validates such as:
validate :upc_check
def upc_check
if !upc.nil?
if !upc.ean?
errors.add(:upc, 'is not a valid UPC.')
else
upc = upc.strip
end
end
end
The strip call is just an example as it's a string. I'll actually be removing the dashes in the upc.
The above code doesn't work so well as it doesn't actually save it. I had a look at triggering a method like
after_validation :normalize_upc
def normalize_upc
upc = upc.strip
end
..but the above doesn't work either.
What do you guys do to validate and transform data after validation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会让验证器变得严格,然后使用 before_validation 过滤器进行任何必要的转换。
I would make my validator strict, and then use a before_validation filter to do any necessary transformations.
我建议覆盖 upc 模型中的 setter 方法,并且不要使用单独的方法对其进行标准化。这可以通过以下方式完成:
编辑:
我还将清理您的验证方法以删除此功能,如下所示:
I would recommend overriding the setter method in your model for upc and not having a separate method for normalizing it. This would be accomplished with something like:
Edit:
I would also clean up your validation method to remove this functionality like so: