Looping through an ActiveRecord array
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

Here is the code in my controller.rb:

@user_ids = Favorite.select(:user_id).limit(5).all

This returns the following output

[#<Favorite user_id: 1488>, #<Favorite user_id: 16625>, #<Favorite user_id: 1510>,  #<Favorite user_id: 1519>, #<Favorite user_id: 1517>]

Hi, I'm new to ruby/rails and i'm wondering if there's a clean way I can grab these user_ids and put them into an array?

Here is my failed attempt that will further demonstrate what I'm trying to achieve:

a = @user_ids.to_s
b = a.split.last.gsub(/\D/, "") 
#would do this 5x to get the different ids then add them to an empty array. 

In this case the output is: 1517

awarded to sguha

Crowdsource coding tasks.

3 Solutions

Winning solution

@user_ids.map(&:user_id) will give you all the ids in an array

Check out http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-map for more information on this method

Sigh...if only I read the docs more thoroughly. Thanks @sguha!
bigthyme over 6 years ago

@user_ids = Favorite.limit(5).map(&:user_id) is what you want

@magicmarkker thanks for the reply magic, but sguha commented first. Cheers!
bigthyme over 6 years ago
using Favorite.select(:user_id).limit(5).all will select only the user_id column from the table in mysql so that will limit the communication between the DB and the application if that is truly the only column needed in this case.
sguha over 6 years ago
@sguha yep, that's what he asked for in his post.
magicmarkker over 6 years ago

@user_ids = Favorite.limit(5).pluck(:id) give you the array with id's.

Check out http://apidock.com/rails/ActiveRecord/Calculations/pluck for more information on this method

View Timeline