Reputation: 237
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?
Upvotes: 2
Views: 342
Reputation: 14038
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
).
Upvotes: 1
Reputation: 10018
You need to splat array
Student.joins(:courses).where(@params.joins(','), *@values)
Upvotes: 2
Reputation: 5998
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
Upvotes: 2