2

in my Rails project I am trying to use the following query in a search form_tag

Student.joins(:courses).where(@params.joins(','), @values)

where params and values are dynamically constructed arrays since there are some optional parameters in the search. An example from my code:

  if params[:date_begin] != ''
    @params.push " courses.date_begin  >=  ? "
    @values.push params[:date_begin]
  end

The problem is the @values array is being considered as one argument and raises this error:

wrong number of bind variables (1 for 2)

How do I tell it to consider the array elements separately?

3 Answers 3

2

What about build query this way:

scope = Student.joins(:courses)

if params[:date_begin].present?
  scope = scope.where(" courses.date_begin  >=  ? ", params[:date_begin])
end

scope
Sign up to request clarification or add additional context in comments.

Comments

2

You need to splat array

Student.joins(:courses).where(@params.joins(','), *@values)

2 Comments

I ended up using the above answer but yours too works great. Thanks a lot
This answer better answers the original question and IMO is cleaner
1

You can unpack the array like so:

Student.joins(:courses).where(@params.join('AND'), *@values)

(Note you also need to change joins to join and the comma to AND).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.