Rails:在params中更改属性的值 [英] Rails: change the value of a an attribute in params
问题描述
我有一个输入(价格
)的表单,用户填写了以下值: 12,50
或 110,90
(法国价格)。
I have a form with an input(price
) that a user fills with values like: 12,50
or 110,90
(French prices).
因此在控制器中,我这样做了: @quote = current_user.company.quotes.build!(params [:quote])
So in the controller I do : @quote = current_user.company.quotes.build!(params[:quote])
问题在于,rails以小数点表示 US
的方式。因此它以价格 12.00
或 111.90
The problem is that rails behaives with the decimals in the US
way. So it saves the quote with the price 12.00
or 111.90
那我如何告诉Rails真正考虑欧洲十进制版本?
So how do I tell rails to actually consider the european version of decimals?
谢谢。
更新
解决方案是将此方法添加到 Quote
模型中。
The solution is to add this method to the Quote
model.
def price=(data) write_attribute(:price, data.to_s.gsub(',', '.')) end
这将用,
>。。
This will replace ,
with .
. Thanks Olivier for the hint.
推荐答案
因为您实际上是在处理小数,所以在存储之前将其转换为小数12,50-> 12.5然后您可以轻松地对其执行任何算术运算。
Because you are actually dealing with decimals convert to a decimal 12,50 -> 12.5 before storing it you can then easily perform any arithmetic on it.
这将是params中的字符串,因此您可以使用sub来代替。您可以在模型中通过重写setter price =
方法来做到这一点。
It will be a string in the params so you can use sub to replace , with . You could do this in the model by overriding the setter price=
method.
将其转换为12,50 in显示时视图。
Convert it to 12,50 in the view when displaying it.
这篇关于Rails:在params中更改属性的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!