Shruthi R Shruthi R - 3 months ago 12
Ruby Question

Rails - How to query by multiple ids(array)

In rails 4, I am trying to access a ActiveRecord relation using multiple ids.

Ids are coming as

Parameters: {"ids"=>"[55, 56]"}
. In controller I am using it as
User.where(:id=>params[:ids])
but this query returns zero results.

View path is like
user_posts_path(:ids=>[5, 6])


Right now
params[:ids].class.name
is
String
. How to make it only as an array?

Answer

Try

User.where(:id=> JSON.parse(params[:ids]))

But I'd try to pass these ids as an array, not an array in a string, if possible.