【发布时间】:2015-01-11 08:18:48
【问题描述】:
我在 Rails4 项目中使用hstore_translate 来处理 我的 I18n 需求。
假设我有以下模型:
class Thingy < ActiveRecord::Base
translates :name
end
在迁移中定义的表为
create_table :thingies do |t|
t.hstore name_translations
end
add_index ::thingies, :name_translations, using: :gin
在我的 Ruby 代码中,我希望检索具有特定 locale 名称的 Thingies 的所有 names 和 ids 的列表。
以前,在我的Thingy 有一个本地化的name 之前,我可以这样做
thingies = Thingy.order(:name).pluck(:id, :name)
现在我在做
thingies = Thingy.where("name_translations ? 'en'").order("name_translations -> 'en'").to_a.map do |t|
{id: t.id, name: t.name}
end
但我不禁觉得有一种方法可以更好地利用 Postgres 在一行代码中完成这一切,而无需在 Ruby 中调用循环。
【问题讨论】:
-
你试过
Thingy.order("name_translations -> '#{params[:locale]}')吗?
标签: ruby-on-rails postgresql activerecord rails-i18n hstore