Search code examples
ruby-on-rails-4searchargumentsfinder

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


I’m using Rails 4.2.3. I’m having trouble passing a variable number of search criteria to my Rails finder method. I have

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

But this results in the error

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 = ?

I think Rails is treating my “search_values” array as a single value but I want it to pass each value of the array as an argument into the search condition. How do I fix the above?


Solution

  • If I've read the question right, this boils down to

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

    Throwing an error about an incorrect number of bind variables. To unpack an array and use its values as individual arguments you use the splat operator:

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