[英]Rails identification of leading zeroes when automatically converting a string to an integer in a model
I have a model in Rails which accepts an integer value. 我在Rails中有一个接受整数值的模型。 Sometimes it's submitted as a string with leading zeroes and I'd the option to output it as a string later with the leading zeroes.
有时,它以带前导零的字符串形式提交,我选择稍后以带前导零的字符串形式输出。
I could store as a string in the db instead but I was wondering if there was another way. 我可以将其存储为字符串,但是我想知道是否还有另一种方法。 Simplified code below.
下面的简化代码。
s = Speed.create(value: "03", measurement: "KPH")
expect(s.value).to eq(3)
expect(s.to_s).to eq("03KPH") # FAILS, returns "3KPH"
expect(s.padding).to eq(1) # FAILS, returns 0
I have a padding field in the database in which to store the number of leading zeroes. 我在数据库中有一个填充字段,用于存储前导零的数量。
If you want to keep original information about the string, then store it as a string rather than an integer. 如果要保留有关字符串的原始信息,则将其存储为字符串而不是整数。 You can then add a method to translate it to an integer if needed, or just call "to_i" on it when you use it and want to use it as a number.
然后,您可以根据需要添加一个将其转换为整数的方法,或者在使用它并希望将其用作数字时在其上调用“ to_i”。
You could change your test to 您可以将测试更改为
s = Speed.create(value: "03", measurement: "KPH")
expect(s.value.to_i).to eq(3)
expect(s.to_s).to eq("03KPH")
expect(s.padding).to eq(1)
You can manually set/get your active record attributes by doing something like below, 您可以通过以下操作手动设置/获取活动记录属性,
class Speed < ActiveRecord::Base
def value=(i)
self.value = i
end
def value
value.to_i
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.