来自Rails中的非ActiveRecord模型的数据库查询

时间:2012-10-03 13:24:45

标签: ruby-on-rails ruby-on-rails-3 hstore

在使用Rails 3.2和Postgres hstore构建应用程序时,我遇到了一个非ActiveRecord模型的问题(目前使用ActiveAttr,但对其他选项开放)。简而言之,我需要查询数据库以检索hstore中的密钥集。据我所知,这只能通过直接的非ActiveRecord :: Query语句实现。

我目前的代码如下:

def self.keys(query)
  # FIXME Need to determine how to sanitize input
  sql = "SELECT DISTINCT key FROM ( SELECT skeys(data) AS key from \"products\" ) AS keys"
  if(query && !query.empty?)
    sql += " WHERE lower(key) LIKE '%#{query.downcase}%'"
  end
  ActiveRecord::Base.connection.select_values(sql)
end

这样可行,但不会清理输入query。如果我尝试创建一个数组而将关键行更改为sql += " WHERE lower(key) LIKE ?"我在日志中出现此错误:

Could not log "sql.active_record" event. NoMethodError: undefined method `squeeze' for #<Array:0x007fd9968704e8>
TypeError: wrong argument type Array (expected String): ["SELECT DISTINCT key FROM ( SELECT skeys(data) AS key from \"products\" ) AS keys WHERE lower(key) LIKE ?", "%o%"]

是否可以在外部调用适当的清理方法,或者至少在我的模型中执行相同的逻辑?

0 个答案:

没有答案