Skip to content

Instantly share code, notes, and snippets.

@sobstel
Created April 18, 2017 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sobstel/e102901af07bb0390ca67af914916b5d to your computer and use it in GitHub Desktop.
Save sobstel/e102901af07bb0390ca67af914916b5d to your computer and use it in GitHub Desktop.
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