Created
June 11, 2018 23:28
-
-
Save dtelaroli/6b4a6115cabc2930ecc6ecc44d943f2c to your computer and use it in GitHub Desktop.
Use concern to translate models with globalize
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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') | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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