0

I'm fairly new to Rails but have a fairly extensive programming background. I'm working on a project and my partner told me to call this function:

UserStats.select("DISTINCT(car_id) as car_id").where(["age |~ >?", 25]).map(&:car_id)

He told me this statement will get me an array user car id's for all users over 25.

Now I'm not really sure I fully understand what's going on in this line. I know the UserStats is a class but I don't see a select method.

  1. Is that an already defined method? Can I just call this line in a ruby function or do I need to initialize the class first?

  2. Does the car_id need to actually be `:car_id"? Any help would be greatly appreciated.

bronislav
  • 782
  • 7
  • 27
user2604504
  • 697
  • 2
  • 14
  • 29

2 Answers2

2

UserStats is a model. It represents a table in your database.

UserStats.select is a query method to extract result from your model (and eventually database table). Read here: http://guides.rubyonrails.org/active_record_querying.html

where is a clause to your select which is equivalent to mysql where clause.

result returned is an array, map creates a new array containing the values returned by the block in your case with car_ids

Above all run this code in your rails console and you can see an equivalent database query generated for it. That may help you understand better. Something like:

SELECT DISTINCT(car_id) as car_id FROM `User_Stats` WHERE (age >= 25)

This should return something like:

[#<UserStat car_id: "Z5w3iefxJh">, #<UserStat car_id: "SADH1243Ng">, ...]

.map(&:car_id) will now sanitize your resultant array as:

 ["Z5w3iefxJh", "SADH1243Ng", ...]
shivam
  • 16,048
  • 3
  • 56
  • 71
1

If the UserStats class inherits from ActiveRecord, select is built in. Ruby makes it really easy to do basic database manipulation through ActiveRecord.

http://guides.rubyonrails.org/active_record_querying.html

JulieC
  • 192
  • 11