Rails API Globalize get all translations

466 views Asked by At

In an API-only rails app using globalize - how do I return all the translations for a model?

ie.

[
    {
        "id": 1,
        "name_ar": "كرستوفر نولان",
        "name_en": "Christopher Nolan",
        "name_fr": "Christopher Nolan"
    },
    {
        "id": 2,
        "name_ar": "ميشيل جوندري",
        "name_en": "Michael Gondry",
        "name_fr": "Michael Gondry"
    },
    // ...
]

I've been searching for quite some time about this but I have failed to find a solution.

2

There are 2 answers

2
Deepesh On

You can do something like this: (not a complete efficient solution but just a try if that helps)

# translated attribute names
attrs = %w[title description]

def translated_attributes(objects, attributes)
  result = []
  objects.each do |obj|
    trans = {}
    obj.translations.each do |tr|
      trans['id'] = obj.id
      attributes.each do |attr|
       trans[attr + '_' + tr['locale']] = tr[attr]
     end
    end
    result << trans
  end
  result
end

translated_attributes(objects, attrs)

Please change the names according to your application and pass the attributes accordingly.

0
Xenos On

You can do something like this:

result = {}
Director.find_each do |director|
  result[:id] = director.id
  director.translations.each { |t| result["name_#{t[:locale]}"], result["description_#{t[:locale]}"] = t.title, t.description }
end

to get

{
    "id": 1,
    "name_ar": "كرستوفر نولان",
    "name_en": "Christopher Nolan",
    "name_fr": "Christopher Nolan",
    "description_ar": "...",
    "description_en": "...",
    "description_fr": "..."
},