1

来自控制器 + 错误的代码:

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) }

现在,我对 ruby​​ 的了解还不够,无法确切知道那条线的作用。我认为它最初与字符串中的百分号有关,但删除它仍然会导致相同的错误。我什至还尝试通过创建多维数组来完全构造字符串,但我仍然遇到同样的错误。

4

1 回答 1

4

您将数组数组传递给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}%"
于 2012-07-23T19:05:32.677 回答