【问题标题】:Errors when passing array or parameters to hstore scope in Rails在 Rails 中将数组或参数传递到 hstore 范围时出错
【发布时间】:2012-09-21 08:38:39
【问题描述】:

我正在尝试在我的 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 查询附加在一起,但运气不佳。有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails postgresql scope hstore


    【解决方案1】:

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

    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
    }
    

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

    【讨论】:

      猜你喜欢
      • 2017-08-17
      • 1970-01-01
      • 2015-04-23
      • 1970-01-01
      • 2018-06-26
      • 1970-01-01
      • 1970-01-01
      • 2015-04-21
      • 1970-01-01
      相关资源
      最近更新 更多