V
V
Vayladion Gognazdiak2017-10-16 21:02:28
Ruby on Rails
Vayladion Gognazdiak, 2017-10-16 21:02:28

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

Both models have title_en and title_ru fields, which store titles in English and Russian, respectively. It is necessary to render certain fields depending on the locale used.
Let's take a controller as an example.
class CitiesController < ApiController

    def show
      render json: City.find(params[:id]), locale: I18n.locale
    end

  end

And serializer
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

The locale parameter is passed to the serializer, depending on which the desired title is issued, but at the same time all fields of the Country model are rendered.
Request: localhost:3000/en/v1/cities/1
{
"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"
}
}

How can I render only certain fields of the associated model depending on the locale?
There is a "headless option":
Add to serializer:
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

But surely there is a more elegant solution. Thanks in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
oh_shi, 2017-10-17
@etspring

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 question

Ask a Question

731 491 924 answers to any question