yerforkferchips
yerforkferchips

Reputation: 1985

Validating inclusion in available locales

I have a database field on my Company mode which specifies a company's locale. I want to validate the value of it to be contained in the available locales of I18n, and I found the inclusion validation of Rails to fit this task.

But when I use

class Company < ActiveRecord::Base
  validates :locale, inclusion: { in: I18n.available_locales.map { |l| l.to_s } }
end

(the map call is because I18n.available_locales returns an array of symbols, not strings, so we need to convert them here)

the locale de, which is available when I call I18n.available_locales from the Rails console, is not valid. What do I do?

Upvotes: 2

Views: 973

Answers (1)

yerforkferchips
yerforkferchips

Reputation: 1985

The problem here is that I18n.available_locales is evaluated once, when the Company class is loaded. Apparently, not all locales are available at that time. What you need to do is to call available_locales dynamically, and you can do it with a proc:

validates :locale, inclusion: { in: proc { I18n.available_locales.map { |l| l.to_s } }

This will be evaluated on runtime, and all your locales will be available.

Upvotes: 3

Related Questions