Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 333
Shruthi R Avatar asked Dec 25 '22 02:12

Shruthi R


2 Answers

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.

like image 114
Ursus Avatar answered Jan 08 '23 09:01

Ursus


Rails has a built in notation to pass arrays through the query string.

Started GET "/users?ids[]=1&ids[]=2&ids[]=3" for ::1 at 2016-08-19 12:08:42 +0200
Processing by UsersController#index as HTML
  Parameters: {"ids"=>["1", "2", "3"]}

When you use some_key[]=1&some_key[]=2 notation Rails will merge all the some_key parameters into an array.

Passing a array to the path helper will generate the correct request URL.

irb(main):012:0> app.users_path(ids: [1,2,3])
=> "/users?ids%5B%5D=1&ids%5B%5D=2&ids%5B%5D=3"
# for clarity
irb(main):013:0> CGI.unescape app.users_path(ids: [1,2,3])
=> "/users?ids[]=1&ids[]=2&ids[]=3"

Using JSON.parse is just masking a bug in your application with a hacky fix.

What is most likely going wrong in your case is that the input to users_path(ids: some_variable) is a string and not an array as expected.

irb(main):014:0> CGI.unescape app.users_path(ids: "[1,2,3]")
=> "/users?ids=[1,2,3]" # this will not be treated as an array!
  • https://coderwall.com/p/uh8kiw/pass-arrays-objects-via-querystring-the-rack-rails-way
like image 25
max Avatar answered Jan 08 '23 09:01

max