-
Type:
Improvement
-
Resolution: Fixed
-
Priority:
Unknown
-
Affects Version/s: None
-
Component/s: None
-
None
-
None
-
Fully Compatible
-
None
-
None
-
None
-
None
-
None
-
None
When using I18n fallbacks, localized fields will consider an empty-string value as a "valid" value to which to fallback.
For example:
car.name_translations = { en: "Camaro", fr: "" }
I18n.locale = :fr
car.name #=> ""
This is fine i.e. expected I18n fallback behavior, however, using Rails forms, you tend to get blank values persisted in text fields inadvertently. To remedy it, I remove blank values in a before_validation callback on every model that uses localization.
before_validation :clean_localized_fields! def clean_localized_fields! localized_fields = self.class.fields.values.select {|f| f.options[:localize] }.map {|f| f.options[:as] || f.name } localized_fields.each do |f| send(:"#{f}_translations=", send("#{f}_translations").delete_if {|_, v| v.blank? }) end end
I can imagine could be some valid use case to persist empty strings for some translations, however, I've never encountered it after making 200+ localized fields in my app. Perhaps we could add something like this:
field :name, type: String, localized: :present
where localized: :present means to auto-remove blank values (i.e. only keep values if `present?` is true)