Instantly share code, notes, and snippets.

Embed
What would you like to do?
Traductor (rails models translations)
module Translatable
extend ActiveSupport::Concern
included do
translation_class_name = "Translations::#{model_name}Translation"
has_many :translations,
class_name: translation_class_name,
dependent: :delete_all,
inverse_of: model_name.to_s.underscore.to_sym
has_one :current_translation,
-> { where(locale: I18n.locale) },
class_name: translation_class_name,
inverse_of: model_name.to_s.underscore.to_sym
# always include translations if translatable
default_scope -> { includes(:current_translation) }
end
end
# Translation model (connected to translatable model)
module Translation
extend ActiveSupport::Concern
included do
# converts `Translations::CityTranslation` to `city`
translatable_name = model_name.to_s.split('::').last.chomp('Translation').to_s.underscore
belongs_to translatable_name.to_sym, inverse_of: :translations
validates :locale,
presence: true,
length: { is: 2 }
validates "#{translatable_name}_id",
presence: true
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment