Reputation: 12663
In a Rails 3.2 app I have a coffeescript function that returns an array of ID numbers from elements with a 'selected" data attribute.
#view (pseudo code!)
<table id='elems_container' data-url=<%= my_path(@object%) >
<tr data-selected = 'true' data-id = '1'></tr>
<tr data-selected = 'true' data-id = '2'></tr>
<tr data-selected = 'false' data-id = '3'></tr>
<tr data-selected = 'true' data-id = '4'></tr>
</table>
#coffeescript
elems = $("tr[data-selected='true']").map(->
$(this).data "id"
).get()
$.ajax({ url: $('#elems_container').data('url'), dataType: "script", data: { 'selected_ids': elems } })
This returns the following in the logs
Started GET "/my/path?selected_ids%5B%5D=1&selected_ids%5B%5D=2&selected_ids%5B%5D=4
I now want to select these selected ids in the controller
@collection = Model.where('id = ?', params[:selected_ids])
Instead this is returning all Models, not just those listed in the params.
Is the get URL correct, or should a params array look different? What else am I doing wrong?
Upvotes: 1
Views: 225
Reputation: 434785
If you URI-decode your query string, you'll see this:
selected_ids[]=1&selected_ids[]=2&selected_ids[]=4
When Rails sees the brackets, []
, it will create an array in params[:selected_ids]
holding the values from the query string and you'll have ['1','2','4']
in params[:selected_ids]
.
When you have multiple values to check, the SQL you want is:
where id in (1,2,4)
ActiveRecord is smart enough to use the in
operator when you hand it an array like this:
where(:some_column => some_array)
so you should be able to say:
@collection = Model.where(:id => params[:selected_ids])
and get what you're looking for in @collection
.
Upvotes: 2