【问题标题】:returning specific values extracted from an hstore (Postgres + hstore_translate gem)返回从 hstore 中提取的特定值(Postgres + hstore_translate gem)
【发布时间】: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 的所有 namesids 的列表。

以前,在我的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 -&gt; '#{params[:locale]}')吗?

标签: ruby-on-rails postgresql activerecord rails-i18n hstore


【解决方案1】:

我已经通过一些试验和错误解决了这个问题。

thingies = Thingy.where("name_translations ? 'en'")
                 .order("name_translations -> 'en'")
                 .pluck(:id, ("name_translations -> 'en'"))

完成这项工作。

它不是很干,但它有效。

【讨论】:

    猜你喜欢
    • 2014-04-14
    • 1970-01-01
    • 2016-10-23
    • 1970-01-01
    • 2017-10-31
    • 2022-12-16
    • 1970-01-01
    • 2013-09-18
    • 1970-01-01
    相关资源
    最近更新 更多