数组的未定义方法“%”

时间:2012-07-23 18:49:10

标签: ruby-on-rails ruby postgresql activerecord

控制器代码+错误:

def search_conditions
    conditions = []
    if !params[:player_name].nil? && !params[:player_name].empty?
      conditions << ["lower(players.name) LIKE ?", "#{params[:player_name].downcase}%"]
    end
    conditions
end

def index
    @games = Game.joins([:player_one, :player_two]).where(search_conditions)
end

undefined method `%' for ["lower(players.name) LIKE ?", "test%"]:Array
Stack Trace:
activerecord (3.2.6) lib/active_record/sanitization.rb:121:in `sanitize_sql_array'
activerecord (3.2.6) lib/active_record/sanitization.rb:28:in `sanitize_sql_for_conditions'
activerecord (3.2.6) lib/active_record/relation/query_methods.rb:324:in `build_where'
activerecord (3.2.6) lib/active_record/relation/query_methods.rb:136:in `where'
app/controllers/game_controller.rb:5:in `index'

查看堆栈跟踪,我搜索活动记录源,并能够在sanitize_sql_array方法中找到导致问题的行:

statement % values.collect { |value| connection.quote_string(value.to_s) }

现在,我对红宝石知之甚少,不知道该行的确切含义。我认为它最初与字符串中的百分号有关,但删除它会导致相同的错误。我甚至尝试通过创建一个多维数组来完全构造字符串,但我仍然得到同样的错误。

1 个答案:

答案 0 :(得分:3)

您将数组数组传递给where,而不仅仅是数组。这意味着statement被设置为数组,但它期望字符串(%)对字符串进行字符串格式化,例如:"hello %s" % "world" => "hello world")。

conditions = []
conditions << ["lower(players.name) LIKE ?", "#{params[:player_name].downcase}%"]

  => [ ["lower(players.name) LIKE ?", "..."] ] 

更改:

conditions << ["lower(players.name) LIKE ?", "#{params[:player_name].downcase}%"]

为:

conditions.push "lower(players.name) LIKE ?", "#{params[:player_name].downcase}%"