1

我正在尝试在我的 Rails 应用程序中的 hstore 列上创建范围。Product 是一个模型, features 是一个 hstore 类型的属性(使用 Postgresql 9.2)。我的范围类定义如下:

class Product < ActiveRecord::Base
    scope :with_features, lambda {|features| where("foo_id in (?)", features)

仅当您将单个值作为特征传递时,上述范围才有效。数组抛出错误。如下图所示:

Product.with_features('api')
  => [#<Product id: 1, name: "Sample">] 
     # so great success

# now with an array
Product.with_features(['api','mobile'])
  => ActiveRecord::StatementInvalid: PG::Error: ERROR:  argument of WHERE must be type boolean, not type record 
    # so no good, this query will work as usual if features isn't of type hstore

在 Rails 3.2 中,当涉及数组时,似乎对 postgres hstore 类型的支持受到限制(我使用的是https://github.com/softa/activerecord-postgres-hstore)。我一直在尝试使用每个循环的一些解决方案来将 AND 查询附加在一起,但运气不佳。有任何想法吗?

4

1 回答 1

0

这是我想出的一个很好的解决方案:

scope :with_features, lambda { |features| 

  #store the composed scope in local variable to build on
  composed_scope = self.scoped

  # if array, then loop through each
  if features.instance_of?(Array)
    features.each do |feature|
      composed_scope = composed_scope.where("features ? :key", :key => feature)
    end

  # otherwise, it's a single string parameter, parse as normal
  else
    composed_scope = composed_scope.where("features ? :key", :key => features)
  end

  # return the newly built composed scope
  composed_scope
}

现在上面的两个示例查询都返回了预期的结果。

于 2012-09-29T23:42:13.223 回答