Skip to content

Instantly share code, notes, and snippets.

@dtelaroli
Created June 11, 2018 23:28
Show Gist options
  • Save dtelaroli/6b4a6115cabc2930ecc6ecc44d943f2c to your computer and use it in GitHub Desktop.
Save dtelaroli/6b4a6115cabc2930ecc6ecc44d943f2c to your computer and use it in GitHub Desktop.
Use concern to translate models with globalize
# include this partial inside your form
= f.fields_for :translations do |t|
= t.hidden_field :id
= t.text_field :locale, readonly: true, label: t('label.locale')
= t.text_field :name, required: true, label: t('label.name')
class MyModel < ApplicationModel
# include the concern in all models which should be translated
include Translations
# configurate the translation
translate :name, touch: true, required: true
end
class MyModelsController < ApplicationController
def new
@my_model = MyModel.new.with_locales
end
private
def my_model_params
params.require(:my_model).permit(:name, translations_attributes: [:id, :locale, :name])
end
end
module Translations
extend ActiveSupport::Concern
included do
# class method
def self.translate(field, args)
# delegate to globlalize method the configuration
translates field, args
# to use fields_for at views
accepts_nested_attributes_for :translations
end
end
# instance method
def with_locales
[:en, :br].each do |locale|
translations.build(locale: locale)
end
self
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment