4

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?

3 Answers 3

8

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.

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

1 Comment

Thank You. It is working fine. I am passing it as an array only but it is taking as a string inside the params.
2

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!

Comments

0

Something worth noting about the answers above: They do not maintain order, and they do not retrieve duplicates. To maintain order, newer Rails versions allow the following:

User.find(32, 12, 4,2,1,2,5).map(&:id)
=> [32, 12, 4, 2, 1, 5]

I'm not aware of any way to re-insert the duplicates back beyond manually re-populating the list.

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.