当我尝试编写 Rails 查找器方法时获取 "wrong number of bind variables"

Getting "wrong number of bind variables" when I'm trying to write a Rails finder method

我正在使用 Rails 4.2.3。我无法将可变数量的搜索条件传递给我的 Rails 查找器方法。我有

    user = current_user
    search_criteria = ["my_objects.user_id = ?"]
    search_values = [user.id]
    start_date = params[:start_date]
    if start_date.present?
      start_date_obj = Date.strptime(start_date, "%m/%d/%Y")
      search_criteria.push("my_objects.start_date >= ?")
      search_values.push(start_date_obj)
    else
      start_date = my_object.find_user_first_my_object_date(user)
      @default_start_date = start_date.to_time.strftime("%m/%d/%Y") if start_date.present?
    end
    end_date = params[:end_date]
    if end_date.present?
      end_date_obj = Date.strptime(end_date, "%m/%d/%Y")
      search_criteria.push("my_objects.end_date <= ?")
      search_values.push(end_date_obj)
    else
      end_date = my_object.find_user_last_my_object_date(user)
      @default_end_date = end_date.to_time.strftime("%m/%d/%Y") if end_date.present?
    end
    distance = params[:distance]
    if distance.present?
      distance_parts = distance.split(" ")
      search_criteria.push("my_objects.distance = ?")
      search_criteria.push("my_objects.distance_unit_id = ?")
      search_values.push("#{distance_parts[0]}")
      search_values.push("#{distance_parts[1]}")
    end
    @user_my_objects = MyObjectTime.joins(:my_object).where(search_criteria.join(" AND "), search_values)
                                           .order("my_objects.day")

但这会导致错误

wrong number of bind variables (1 for 5) in: my_objects.user_id = ? AND my_objects.start_date >= ? AND my_objects.end_date <= ? AND my_objects.distance = ? AND my_objects.distance_unit_id = ?

我认为 Rails 将我的“search_values”数组视为单个值,但我希望它将数组的每个值作为参数传递到搜索条件中。我该如何解决上述问题?

如果我没看错问题,这可以归结为

values = ['a', 'b', 'c']
SomeModel.where("foo = ? AND bar = ? AND baz = ?", values)

抛出有关绑定变量数量不正确的错误。要解压数组并将其值用作单独的参数,您可以使用 splat 运算符:

SomeModel.where("foo = ? AND bar = ? AND baz = ?", *values)