Answer the question
In order to leave comments, you need to log in
How is object fields serialized based on locale in rails?
Good day.
ENV: ruby 2.4.1, Rails 5.1, active_model_serializer
There are two models:
class Country < ApplicationRecord
has_many :cities
end
class City < ApplicationRecord
belongs_to :country
end
class CitiesController < ApiController
def show
render json: City.find(params[:id]), locale: I18n.locale
end
end
class CitySerializer < ActiveModel::Serializer
attributes :id, :title
belongs_to :country
def title
case @instance_options[:locale]
when 'ru'
object.title_ru
when 'en'
object.title_en
end
end
end
{
"id": 1,
"title": "Moscow",
"country": {
"id": 1,
"title_en": "Russia",
"title_ru": "Россия",
"created_at": "2017-10-12T17:14:31.971Z",
"updated_at": "2017-10-12T17:14:31.971Z"
}
}
def country
case @instance_options[:locale]
when 'ru'
{ country_id: object.country.id, title: object.country.title_ru }
when 'en'
{ country_id: object.country.id, title: object.country.title_en }
end
end
Answer the question
In order to leave comments, you need to log in
I18n.locale does not need to be passed as a parameter, it should be available inside the serializer anyway. Keeping translations in separate columns is the most "inelegant" solution, which will be harder to use and maintain.
Alternative options:
1) store translations in separate tables
2) store all translations in one column in jsonb format
3) you have already been offered separate yaml files with translations
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question