2

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

这些工作非常好:

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 查询?

4

3 回答 3

1

Squeel 通过使用反引号 (`) 来支持 SQL 文字。

像下面这样的东西可能会起作用:

Person.where{(id == my{@person.id}) & (`preferences @> send_me_junk_email=>yes`)}

当使用反引号时,Squeel 会下拉一个抽象层并直接执行 SQL。

http://erniemiller.org/2012/05/30/sql-literals-in-squeel-or-overriding-backticks-in-ruby/

于 2012-10-21T21:17:44.213 回答
1

我只是深入研究了这一点。答案似乎在这个文件中,基本上你可以在这里添加你自己的操作。

此示例用于@>搜索 PostgreSQL 数组(在此演示文稿中进行了演示)。

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

放入这个猴子补丁后,假设有一个具有数组字段的Note模型,以下 Squeel 语句成为可能。tags

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

应该生成如下所示的 SQL:

"SELECT \"notes\".* FROM \"notes\"  WHERE \"notes\".\"tags\" @> '{first tag,second tag}'"
于 2014-01-03T21:16:15.127 回答
1

尝试使用sequel hstore gem,这增加了对 hStore 到 Sequel 的支持

于 2012-09-05T19:06:46.607 回答