在我的rails应用程序中,我有一个模型(category.rb),其配置如下:
id,名称,语言环境
1,社交性,en
2,审慎与美味,en
3,社会性,zh-TW
4,“谨慎性,细腻性”,zh-TW
我想知道不同语言环境的初始ID,例如,:en的初始ID为“ 1”,而“:zh-TW”的ID为“ 3”。除了在应用程序中进行硬编码以定义初始ID之外,没有任何gem或方法可以识别初始ID?这样以后,当我将新记录添加为5,例如Sociabilidad时,无需硬编码即可正确获取ID?
请告知。谢谢。
答案 0 :(得分:0)
我将使用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
在Rails控制台中:
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>]
这是我用ActiveRecord方式包装的SQL答案。