【问题标题】:select single property in hstore field with Rails 4.1使用 Rails 4.1 在 hstore 字段中选择单个属性
【发布时间】:2014-08-10 07:03:25
【问题描述】:

我正在使用带有 Rails 4.1 的 Postgres 9.3。

假设我有一个带有 properties hstore 列的表。

我现在想在一个范围内(或其他地方......)的 hstore 列中选择一个键

我尝试了什么: Model.select("properties -> 'category'")

发生了什么:Rails 给了我一个这样的数组:

[#<Model id: nil>,
 #<Model id: nil>,
 #<Model id: nil>,
 #<Model id: nil>]

我想要什么:

[#<Model id: nil, category: 'foo'>,
 #<Model id: nil, category: 'bar'>,
 #<Model id: nil, category: 'baz'>,
 #<Model id: nil, category: 'foo'>]

【问题讨论】:

  • Model.where("properties ? 'category'") 工作吗?
  • 这并没有完成我想做的事情..

标签: ruby-on-rails ruby postgresql ruby-on-rails-4 hstore


【解决方案1】:

试试:

=>  Model.where("properties @> hstore(?, ?)", 'key', 'value').select(:category)
=> [#<Model id: nil, category: 'foo'>]

【讨论】:

  • 虽然这可能会回答问题,但解释代码的作用以及为什么这是 OP 的最佳解决方案将大大改进此答案,并帮助未来的访问者。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-02
  • 2015-07-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多