如何防止rails整数转换为二进制? [英] How do I keep my rails integer from being converted to binary?

查看:143
本文介绍了如何防止rails整数转换为二进制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如您可以在图像中看到的那样,我有一个用户模型,@ user.zip存储为整数用于验证目的(即,只存储数字等)。当我发现我的示例邮政编码(00100)被自动转换为二进制文件并最终为数字64时,我正在排除错误。

As you may be able to see in the image, I have a User model and @user.zip is stored as an integer for validation purposes (ie, so only digits are stored, etc.). I was troubleshooting an error when I discovered that my sample zip code (00100) was automatically being converted to binary, and ending up as the number 64.

关于如何为了防止这种情况发生?我是Rails的新手,我花了几个小时才弄清楚这个错误的原因,正如你可能想象的那样:)

Any ideas on how to keep this from happening? I am new to Rails, and it took me a few hours to figure out the cause of this error, as you might imagine :)

我无法想象任何其他这里的信息会有所帮助,但如果不是,请通知我。

I can't imagine any other information would be helpful here, but please inform me if otherwise.

推荐答案

这不是二元的,这是 octal

在Ruby中,任何以0开头的数字都将被视为八进制数。你应该查看 Ruby数字文字要了解更多信息,请点击这里:

In Ruby, any number starting with 0 will be treated as an octal number. You should check the Ruby number literals to learn more about this, here's a quote:


您可以使用特殊前缀来写入十进制,十六进制,八进制或二进制数字格式。对于十进制数字,使用前缀0d,对于十六进制数字,使用前缀0x,对于八进制数字,使用前缀0或0o,对于二进制数字,使用前缀0b。数字的字母组成部分不区分大小写。

You can use a special prefix to write numbers in decimal, hexadecimal, octal or binary formats. For decimal numbers use a prefix of 0d, for hexadecimal numbers use a prefix of 0x, for octal numbers use a prefix of 0 or 0o, for binary numbers use a prefix of 0b. The alphabetic component of the number is not case-sensitive.

对于您的情况,您 将zipcodes存储为数字。不仅在数据库中,而且即使变量不将它们视为数值。相反,将它们存储并视为字符串。

For your case, you should not store zipcodes as numbers. Not only in the database, but even as variables don't treat them as numeric values. Instead, store and treat them as strings.

这篇关于如何防止rails整数转换为二进制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆