我有一个 User
类,它有一个 hstore
属性 :preferences
。如果我想找到他们首选项中 startpage
键为 nil
的所有用户,我可以这样做:
User.where("preferences @> 'startpage=>NULL'")
我如何构建该查询以避免 SQL 查询注入(inject)?
尝试过:
User.where("preferences @> :key '=>NULL'", key: 'startpage')
User.where("preferences @> :key IS 'NULL'", key: 'startpage')
User.where("preferences @> :key IS NULL", key: 'startpage')
User.where("preferences @> ? IS NULL", 'startpage')
没有运气。有人知道怎么做吗?
最佳答案
@>
运算符需要两边的 hstores。当你说:
some_hstore @> 'startpage=>NULL'
PostgreSQL 将隐式添加 ::hstore
强制转换,就像您说的那样:
some_hstore @> 'startpage=>NULL'::hstore
但是还有其他方法可以创建 hstore。来自fine manual :
Function:
hstore(text, text)
Return Type:hstore
Description: make single-item hstore
因此您可以切换到更明确的 hstore(text, text)
函数,让 ActiveRecord 使用占位符和字符串执行其正常操作:
User.where("preferences @> hstore(:key, null)", :key => 'start page')
关于ruby-on-rails - Hstore 上的 Rails Postgres 查询以避免 SQL 注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34667828/