我正在尝试在我的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查询附加在一起,而不是运气。有什么想法吗?
答案 0 :(得分: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
}
现在,上述两个示例查询都会返回预期结果。