-2

Hi I'm new to Ruby on Rails. I created Users with device, on profile creation the user enters a numeric field that's limited to 5 numbers. Now I need to get the most common numbers from all users. How could I do that?

I want to show most common numbers in my admin controller, please help.

MZimmerman6
  • 8,445
  • 10
  • 40
  • 70
Lorenzo Sinisi
  • 450
  • 5
  • 8
  • Please describe what you've tried so far. The nature of StackExchange is that we help people solve specific bugs in their code. You are less likely to get someone to teach you basic strategies (though you could get lucky) – New Alexandria Oct 17 '13 at 14:35
  • You should google for "sql grouping count" to group your users by the numeric field and then get the count of each value. – Jesse Wolgamott Oct 17 '13 at 15:19

1 Answers1

1

You can get the array of numeric fields by doing

array = User.all.map(&:numeric_field)   # assuming there is a numeric_field column

Then you can get the most common number (called the "mode") with several different methods, referenced by this post: Ruby: How to find item in array which has the most occurrences?

If you have a lot of users, this approach can hog memory, in which case you can do the operation in batches:

array = []
User.find_in_batches do |users|
  array += users.map(&:numeric_field)
end

And then just use the array as before.

Community
  • 1
  • 1
Tyler
  • 11,272
  • 9
  • 65
  • 105