Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bbonamin/1379229 to your computer and use it in GitHub Desktop.
Save bbonamin/1379229 to your computer and use it in GitHub Desktop.
RailsAdmin and Globalize3

RailsAdmin and Globalize3

I have a project where I need translated content. Therefore I use globalize3, wich stores its translated attributes in a seperate table that belongs to the original model. And I use RailsAdmin for painless record management.

It took me some time to figure out how to get those working together, but eventually I found a solution that is non invasive and still ok to work with.

The translated model

In my case there is a Snippet class. It holds content for static pages or text passages on the website. There is a good README for globalize3 for installation instructions and documentation.

class Snippet < ActiveRecord::Base
  validates :path, presence: true, uniqueness: true, format: /^[-_a-z0-9\/]*$/

  translates :title, :content do
    validates :title, presence: true
    validates :content, presence: true
  end
  has_many :snippet_translations
  accepts_nested_attributes_for :snippet_translations
end

Setup a model for your translation tables

Usually you won't create a class for your translation tables. Globalize takes care of your translations and connects attributes magically to your main model. But in our case we want to make use of RailsAdmin. Make sure you define the proper belongs_to association. The locale_enum method adds some sugar to the RailsAdmin forms in order to fill the locale field with a dropdown of all your available locales.

class SnippetTranslation < ActiveRecord::Base
  belongs_to :snippet

  def locale_enum
    I18n.available_locales
  end
end

Configure RailsAdmin to make use of the translation table class

When having RailsAdmin in your app, usually there is an initializer for all the configurations. The only important thing, that I have defined is the object_label_method on the Snippet. Everything else is just added flavor, e.g. I'm using a WYSIWYG editor for the content field.

RailsAdmin.config do |config|
  config.included_models = [Snippet, SnippetTranslation]
  config.model SnippetTranslation do
    edit do
      include_all_fields
      field :content, :text do
        ckeditor true
      end
    end
  end
  config.model Snippet do
    object_label_method { :path }
  end
end

That is how it looks like

Here is a series of screenshots

Have fun!

Lukas

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment