2012-09-05 33 views
2

我想为我的Rails应用程序(v 3.2.6)使用Squeel gem(基于Arel)。我的hstore列被称为属性。Rails:我如何使用hstore使用Squeel?

这些工作完全正常:

User.where{(firstname == 'Ryan') & (lastname == 'Bates')} 
User.where{"properties @> ('male' => '1')"} 

第二个例子是一个普通的Postgres的查询,因为Squeel似乎并不支持hstore功能。

这些不工作:

User.where{"properties @> ('male' => '1')" & firstname == 'Ryan'} 
User.where{("properties @> ('male' => '1')") & (firstname == 'Ryan')} 

错误:

NoMethodError: undefined method `&' for "properties @> ('male' => '1')":String 

我明白的错误,但我不知道该怎么胶囊我hstore查询。有没有更好的方法用Squeel或Arel构建hstore查询?

感谢您的帮助!

回答

1

尝试使用sequel hstore gem,这增加了支持hStore到续集

+0

谢谢。看起来我必须换成续集。 – Railsana

+1

你不需要续集hstore gem,Sequel已经附带了一个pg_hstore扩展,现在增加了对不少版本的支持。 –

+1

我想你会把'Squeel'和'Sequel'混淆起来。 OP询问[Squeel](https://github.com/activerecord-hackery/squeel) – nocache

1

我刚刚挖出了这个。答案似乎在this file,基本上你可以在这里添加你自己的操作。

本示例使用@>来搜索PostgreSQL数组(demonstrated in this presentation)。

module Squeel 
    module Nodes 
    module Operators 
     def within *list 
     list = "{#{list.map(&:to_s).join(',')}}" 
     Operation.new self, :'@>', list 
     end 
    end 
    end 
end 

把这个猴的贴剂中后,下面的Squeel语句成为可能,假设存在具有一个tags阵列字段Note模型。

Note.where { tags.within 'first tag', 'second tag' } 

哪些应该生成SQL,看起来像这样:

"SELECT \"notes\".* FROM \"notes\" WHERE \"notes\".\"tags\" @> '{first tag,second tag}'" 
+0

不错!你有没有考虑过打开一个pull request来为Squeel贡献这个功能? –