0

數據庫採用英語和格式的值編號,例如:hourlyrate => 20.90。首次啓動時(默認語言爲英語),輸入表單正確顯示字段的內容。我可以修改和保存,沒問題。 如果我切換到德語,數字將正確顯示爲20,90。如果我編輯此表單上的任何內容,我無法再保存,因爲驗證會將該數字視爲無效。Rails 3/3.1和I18n:在語言之間切換時驗證命中

我的問題是,我必須在保存之前在控制器中執行更正,還是錯過了Rails的某些內置功能?

的代碼的相關部分

助手:

def my_number_with_precision(value) 
    if value 
    # value 
    number_with_precision(value, :precision => 2) 
    end 
end 

驗證:

validates :hourlyrate, :numericality => { :greater_or_equal_than => 0, :message => " is an invalid number or below zero" } 

形式:

<div class="input"> 
    <%= f.text_field :hourlyrate, :value => my_number_with_precision(f.object.hourlyrate) %> 
</div> 

的Gemfile

gem 'rails-i18n' 

回答

0

我想出了以下解決方案之一 - 特定語言代碼:

def parse_i18n(value) 
    if I18n.locale = 'de' 
    value.gsub(',', '.') 
    else 
    value 
    end 
end 

def parse_i18n(value) 
    value.gsub(I18n.t("number.currency.format.unit"),''). 
     gsub(I18n.t("number.currency.format.delimiter"), ''). 
     gsub(I18n.t("number.currency.format.separator"), '.') 
end