Search code examples
mysqlruby-on-railslocale

How to get id number from different locale in model


I have one model (category.rb) in my rails application configured as below:

id,name,locale

1,Sociability,en

2,Prudence and Delicacy,en

3,社會性,zh-TW

4,"謹慎性,細膩性",zh-TW

I would like to know the initial ID for different locale, for example, the initial ID for :en will be "1" and ID for :"zh-TW" will be "3". Instead of hard-coded to define the initial ID in application, is there any gem or method to identify the initial ID? So that in future, when I add new record as 5, Sociabilidad, es, I can get the ID correctly without hard-coded?

Please advise. Thank you.


Solution

  • I'd write this as below using AR:

    class Category < ApplicationRecord
      scope :first_in_locale, ->() {
        joins(<<-SQL)
          JOIN (SELECT locale, min(id) AS id FROM categories GROUP BY locale) b ON b.id = categories.id
        SQL
        .select('categories.*')
        .order('categories.id')
      }
    end
    

    In Rails console:

    2.5.1 :010 > pp Category.first_in_locale
      Category Load (0.9ms)  SELECT categories.* FROM "categories" JOIN (SELECT locale, min(id) as id from categories group by locale) b on b.id = categories.id ORDER BY categories.id
    [#<Category:0x00007fc597e3db68
      id: 1,
      name: "Sociability",
      locale: "en",
      created_at: Sun, 16 Sep 2018 07:47:34 UTC +00:00,
      updated_at: Sun, 16 Sep 2018 07:47:34 UTC +00:00>,
     #<Category:0x00007fc597e3d3e8
      id: 3,
      name: "社會性",
      locale: "zh-TW",
      created_at: Sun, 16 Sep 2018 07:47:34 UTC +00:00,
      updated_at: Sun, 16 Sep 2018 07:47:34 UTC +00:00>]
    

    Here is the SQL answer I wrapped in ActiveRecord way.