public
Last active

RailsAdmin and Globalize3

  • Download Gist
rails_admin_and_globalize3.md
Markdown

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

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: https://github.com/scarfacedeb/rails_admin_globalize_field

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.