{"id":13747632,"url":"https://github.com/spilliton/randumb","last_synced_at":"2025-05-09T09:30:35.670Z","repository":{"id":1601319,"uuid":"2174054","full_name":"spilliton/randumb","owner":"spilliton","description":"Adds ability to pull back random records from Active Record","archived":false,"fork":false,"pushed_at":"2020-05-26T02:35:29.000Z","size":145,"stargazers_count":204,"open_issues_count":2,"forks_count":25,"subscribers_count":4,"default_branch":"master","last_synced_at":"2025-04-27T05:51:17.503Z","etag":null,"topics":["activerecord","randomization"],"latest_commit_sha":null,"homepage":"","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":"itsahappymedium/responsive-email-kit","license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/spilliton.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"MIT-LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2011-08-08T15:19:40.000Z","updated_at":"2024-09-21T17:52:27.000Z","dependencies_parsed_at":"2022-09-06T05:21:52.707Z","dependency_job_id":null,"html_url":"https://github.com/spilliton/randumb","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spilliton%2Frandumb","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spilliton%2Frandumb/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spilliton%2Frandumb/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spilliton%2Frandumb/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/spilliton","download_url":"https://codeload.github.com/spilliton/randumb/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253226270,"owners_count":21874304,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["activerecord","randomization"],"created_at":"2024-08-03T06:01:35.808Z","updated_at":"2025-05-09T09:30:35.435Z","avatar_url":"https://github.com/spilliton.png","language":"Ruby","funding_links":[],"categories":["Ruby"],"sub_categories":[],"readme":"# randumb\n\n[![Gem Version](https://badge.fury.io/rb/randumb.png)](http://badge.fury.io/rb/randumb)\n[![Build Status](https://secure.travis-ci.org/spilliton/randumb.png?branch=master)](http://travis-ci.org/spilliton/randumb)\n[![Code Climate](https://codeclimate.com/github/spilliton/randumb.png)](https://codeclimate.com/github/spilliton/randumb)\n\nrandumb is a ruby gem that allows you to easily pull random records from your database of choice.\n\nRequires ActiveRecord \u003e= 3.0.0 and supports SQLite, MySQL and Postgres/PostGIS (PRs welcome for other DB support).\n\n## Install\n\n``` ruby\n# Add the following to you Gemfile\ngem 'randumb'\n\n# Update your bundle\nbundle install\n```\n\n## Usage\n\nThe most common usage is a scope you can chain along like any other:\n\n``` ruby\nArtist.order_by_rand.first # a random Artist if there are any, otherwise nil\nArtist.order_by_rand.limit(3).all  # an array of three Artists picked at random\nArtist.order_by_rand.limit(1).all  # an array containing one random Artist\n```\n\n### How It Works\n\nrandumb simply tacks an additional ```ORDER BY RANDOM()``` (or ```RAND()``` for mysql) to your query.\n\n## Advanced Usage\n\n### Stacking the Deck\n\nYou can use the ```order_by_rand_weighted``` scope to favor certain records more than others.\n\nFor example, if you want to favor higher-rated Movies, and your\nMovie model has a numeric ```score``` column, you can do any of the the following:\n\n``` ruby\nMovie.order_by_rand_weighted(:score).first\n# returns 1 random movie by:\n# select * from movies ORDER BY (score * RANDOM() DESC) LIMIT 1\n\nMovie.order_by_rand_weighted(:score).limit(10).all\n# returns an array of up to 10 movies and executes:\n# select * from movies ORDER BY (score * RANDOM() DESC) LIMIT 10\n```\n\n### Planting A Seed\n\nIf you wish to seed the randomness so that you can have predictable outcomes, provide an optional integer seed to any of randumb's scopes:\n\n``` ruby\n# Assuming no no records have been added between calls\n# These will return the same 2 artists in the same order both times\nArtist.order_by_rand(seed: 123).limit(2)\nArtist.order_by_rand(seed: 123).limit(2)\n```\n\nOne use case for this scope is when you are paginating through random records.\n\n### Depricated Syntax\n\nA few methods will be going away in randumb 1.0 due to them not really following current active record conventions:\n\n``` ruby\n# working like the active record \"all, first, and last\" methods and passing limit as param\nArtist.has_views.includes(:albums).where([\"created_at \u003e ?\", 2.days.ago]).random(10)\n# dynamic finders for weighted methods\nArtist.random_weighted_by_views\n```\n\n### Random By Id Shuffle\n\nThe adventurous may wish to try randumb's earlier algorithm for random record selection.\nYou cannot apply weighting when using this method and limits/orders also behave a little differently.\n\n``` ruby\n# gimmie 5 random artists that are in the top 100 most viewed\nartists = Artist.limit(100).order(\"view_count DESC\").random_by_id_shuffle(5)\n\n# Executes:\n# select artist.id from artists ORDER BY view_count DESC LIMIT 100\n# in ruby:  artist_ids = ids.shuffle[0..4]\n# select * from artists WHERE id in (artist_ids)\n```\n\n## A Note on Performance\n\nAs stated above, by default, randumb uses a simple approach of applying an order by random() statement to your query.  In many sets, this performs well enough to not really be a big deal.  However, as many blog posts and articles will note, the database must generate a random number for each row matching the scope and this can result in rather slow queries for large result sets.  The last time I tested randumb on a test data set with 1 million rows (with no scopes) it took over 2 seconds.\n\nIn earlier versions of randumb I tried to alleviate this by doing two db queries.  One to select the possibly IDs into an array, and a second with a randomly selected set of those ids.  This was sometimes faster in very high data sets, however, for most sizes I tested, it did not perform significatly better than ORDER BY RAND() and it had the possibility of running out of memory due to selecting all the ids into into a ruby array.\n\nIf you are noticing slow speeds on your random queries and you have a very very large database table, my advice is to scope down your query to a subset of the table via an indexed scope.  Ex:  ```Artist.where('views \u003e 10').order_by_rand.first```  This will result in less calls to RAND() and a faster query.  You might also experiment with the old method by using ```random_by_id_shuffle``` and gauge the resulting speeds.\n\n## ActiveRecord Caching\n\nBy default, ActiveRecord keeps a cache of the queries executed during the current request. If you call `order_by_rand` multiple times on the same model or scope, you will end up with the same SQL query again, which causes the cache to return the result of the last query. You will see the following in your log if this happens:\n\n```\nArtist Load (0.3ms)  SELECT \"artists\".* FROM \"artists\" ORDER BY RANDOM() LIMIT 1\nCACHE (0.0ms)  SELECT \"artists\".* FROM \"artists\" ORDER BY RANDOM() LIMIT 1\n```\n\nFortunately, there is an easy workaround: Just wrap your query in a call to ```uncached```, e.g. ```Artist.uncached { Artist.order_by_rand.first }```.\n\n## Why\n\nI built this for use on [Compare Vinyl][comparevinyl].  Check out the homepage to see it in action :)\n\n[comparevinyl]: http://www.comparevinyl.com/\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspilliton%2Frandumb","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fspilliton%2Frandumb","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspilliton%2Frandumb/lists"}