Rails: change the value of a an attribute in params

亡梦爱人 提交于 2019-12-25 12:41:11

问题


I have a form with an input(price) that a user fills with values like: 12,50 or 110,90 (French prices).

So in the controller I do : @quote = current_user.company.quotes.build!(params[:quote])

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

So how do I tell rails to actually consider the european version of decimals?

Thanks.

UPDATE

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.


回答1:


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.

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.

Convert it to 12,50 in the view when displaying it.



来源:https://stackoverflow.com/questions/9549299/rails-change-the-value-of-a-an-attribute-in-params

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!