Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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
  has_many :snippet_translations
  accepts_nested_attributes_for :snippet_translations

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

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
      field :content, :text do
        ckeditor true
  config.model Snippet do
    object_label_method { :path }

That is how it looks like

Here is a series of screenshots

Have fun!


Hi.. thanks for this gist.
It would be really helpful if you also publish the relevant _form code. How to inplement the select field a.s.on.

I solved this problem without additional models - I'm using the ones that globalize3 created. Like Snipper::Translation.
The only difficulty is that you need to add this model to config.included_model inside rails_admin initializer.

You can find it here:

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