开发者

How to load users based on a list of id's?

开发者 https://www.devze.com 2023-02-23 19:01 出处:网络
I have a list of id\'s, I can store this list in any data type as I will be constructed the id\'s myself.

I have a list of id's, I can store this list in any data type as I will be constructed the id's myself.

How can I fetch all users in this list of id's? I want this to be as fast as possible.

I'm using mysql.

Once I retrieve this list, 开发者_开发问答I want to put the User objects into a hash so I can reference them based on id's like:

user_hash[234]

which will return the user in the hash with the user_id of 234.


user_hash = {}
User.where(:id => [1,2,3,4]).each do |user|
  user_hash[user.id] = user
end


You can select rows using an array of IDs like this:

ids = [1, 2, 3, 4]
users = User.find(ids)

This will return an array of User records. If you'd like to map that to a hash so you can access by ID as you described, something like this would work:

ids = [1, 2, 3, 4]
users = {}

User.find(ids).each do |user|
    users[user.id] = user
end

users[3]    # => #<User id: 3, ...
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号