Rails: change the value of a an attribute in param

2019-09-05 22: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条回答
倾城 Initia
2楼-- · 2019-09-05 22:50

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.

查看更多
登录 后发表回答