Skip to content

Instantly share code, notes, and snippets.

@abelards
Created September 14, 2018 13:07
Show Gist options
  • Save abelards/fd267ea395b1cd7ba77a381ae013e552 to your computer and use it in GitHub Desktop.
Save abelards/fd267ea395b1cd7ba77a381ae013e552 to your computer and use it in GitHub Desktop.
# you: "I would like to randomly people, but I would like famous people to come up more often than non-famous ones."
# me: I expect you to have a :celebrity column with a numeric weight, and arel_extensions installed
# https://github.com/Faveod/arel-extensions/tree/master/lib/arel_extensions
# useful variables
obj = Person
at = obj.arel_table
field = :celebrity
scoring_col_name = 'randomized_score'
scoring_arel = (at[field] * Arel.rand ).as(scoring_col_name)
# let's see our current data
obj.pluck(field) # => [42, 80, 10, 4, 50, 90, 90]
# let's see the SQL request
obj.select(at[:id], scoring_arel).order("#{scoring_col_name} DESC").first(3).to_sql
# "SELECT "people"."id", ("people"."celebrity" * RANDOM()) AS randomized_score FROM "people" ORDER BY randomized_score DESC LIMIT 3"
# let's get a Ruby array of people ID and people randomized fame
obj.select(at[:id], scoring_arel).order("#{scoring_col_name} DESC").first(3).map{|x|
[x.id, x.randomized_score]
}
# [[8, 86.2925770645961], [6, 33.7225229246542], [7, 16.1235050903633]]
# [[8, 77.7499464573339], [4, 61.0140995308757], [7, 51.0964175127447]]
# [[8, 74.7238989081234], [7, 62.6108054537326], [6, 27.6560185477138]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment