Manos
Manos

Reputation: 1501

Rails API Globalize get all translations

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.

Upvotes: 0

Views: 532

Answers (2)

Xenos
Xenos

Reputation: 1

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": "..."
},

Upvotes: 0

Deepesh
Deepesh

Reputation: 6398

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.

Upvotes: 1

Related Questions