获取"错误的绑定变量数量"当我试图编写Rails finder方法时

时间:2016-07-07 19:24:16

标签: ruby-on-rails-4 search arguments finder

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

    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”数组视为单个值,但我希望它将数组的每个值作为参数传递给搜索条件。我该如何解决上述问题?

1 个答案:

答案 0 :(得分:6)

如果我已经正确地阅读了这个问题,那么归结为

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

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

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