2012-09-05 31 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貢獻這個功能? –