{"id":13878067,"url":"https://github.com/the-rubies-way/random-rails","last_synced_at":"2025-11-11T21:19:58.420Z","repository":{"id":181315759,"uuid":"666276139","full_name":"the-rubies-way/random-rails","owner":"the-rubies-way","description":"The most performed gem to get random record you ever seen! Available for Ruby on Rails with PostgreSQL right now!","archived":false,"fork":false,"pushed_at":"2025-10-09T15:34:24.000Z","size":102,"stargazers_count":23,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"master","last_synced_at":"2025-10-13T21:36:48.936Z","etag":null,"topics":["activerecord","performance","postgresql","rails-perfomance","random","ruby","ruby-on-rails","sql"],"latest_commit_sha":null,"homepage":"","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/the-rubies-way.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2023-07-14T05:57:01.000Z","updated_at":"2025-10-09T16:03:35.000Z","dependencies_parsed_at":null,"dependency_job_id":"e904df18-58bf-4a59-a2c9-2156e89bd429","html_url":"https://github.com/the-rubies-way/random-rails","commit_stats":null,"previous_names":["the-rubies-way/random-rails"],"tags_count":3,"template":false,"template_full_name":null,"purl":"pkg:github/the-rubies-way/random-rails","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/the-rubies-way%2Frandom-rails","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/the-rubies-way%2Frandom-rails/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/the-rubies-way%2Frandom-rails/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/the-rubies-way%2Frandom-rails/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/the-rubies-way","download_url":"https://codeload.github.com/the-rubies-way/random-rails/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/the-rubies-way%2Frandom-rails/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":283933759,"owners_count":26918945,"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","status":"online","status_checked_at":"2025-11-11T02:00:06.610Z","response_time":65,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"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","performance","postgresql","rails-perfomance","random","ruby","ruby-on-rails","sql"],"created_at":"2024-08-06T08:01:38.918Z","updated_at":"2025-11-11T21:19:58.409Z","avatar_url":"https://github.com/the-rubies-way.png","language":"Ruby","funding_links":[],"categories":["Ruby"],"sub_categories":[],"readme":"[![lint](https://github.com/the-rubies-way/random-rails/actions/workflows/linter.yml/badge.svg)](https://github.com/the-rubies-way/random-rails/actions/workflows/linter.yml)\n[![test](https://github.com/the-rubies-way/random-rails/actions/workflows/test.yml/badge.svg)](https://github.com/the-rubies-way/random-rails/actions/workflows/test.yml)\n[![Gem Version](https://img.shields.io/gem/v/random-rails)](https://rubygems.org/gems/random-rails)\n\n\u003cp align=\"center\"\u003e\n  \u003cimg width=\"600\" height=\"600\" alt=\"Image Oct 9, 2025, 04_30_33\" src=\"https://github.com/user-attachments/assets/cc522bff-2de6-41f3-b458-83867bf70b26\" /\u003e\n\u003c/p\u003e\n  \n# RandomRails\n\n🚀 The most performant way to get random records from ActiveRecord. Supports **PostgreSQL**, **MySQL**, and **SQLite** with intelligent strategy selection to replace slow `ORDER BY RANDOM()` queries.\n\n## Why RandomRails?\n\nTraditional `ORDER BY RANDOM()` queries become extremely slow on large tables because they require sorting the entire dataset. RandomRails solves this by using:\n\n- **TABLESAMPLE BERNOULLI** for PostgreSQL (ultra-fast on large tables)\n- **Efficient offset-based sampling** for all databases\n- **Intelligent strategy selection** based on table size and database type\n- **Configurable sampling methods** for different use cases\n\n## Performance Comparison\n\nReal-world benchmark results comparing RandomRails with traditional methods (10 iterations each):\n\n| Sample Size     | `ORDER BY RANDOM()` | `User.random()` | `User.sample()` | Performance Gain        |\n| --------------- | --------------------- | ----------------- | ----------------- | ----------------------- |\n| 1,000 users     | 3.8359s               | **0.2157s** | 347.1409s         | **17.79x faster** |\n| 10,000 users    | 6.1273s               | **2.7313s** | 369.7583s         | **2.24x faster**  |\n| 100,000 users   | 31.578s               | **3.6968s** | 369.4334s         | **8.54x faster**  |\n| 1,000,000 users | 171.497s              | **5.3441s** | 373.6102s         | **32.09x faster** |\n\n\u003cimg width=\"1968\" height=\"1180\" alt=\"image\" src=\"https://github.com/user-attachments/assets/3c395cfd-d28f-45d1-92f2-872075552782\" /\u003e\n\n\n**Key Takeaways:**\n\n- RandomRails consistently outperforms `ORDER BY RANDOM()` by 2-32x\n- Performance advantage increases dramatically with table size\n- Traditional `User.sample()` method performs poorly at scale\n\n## Installation\n\nAdd to your Gemfile:\n\n```ruby\ngem \"random-rails\"\n```\n\nOr install directly:\n\n```bash\ngem install random-rails\n```\n\n## Examples\n\n### Basic Usage\n\nGet a single random record:\n\n```ruby\nUser.random\n# =\u003e #\u003cUser id: 42, name: \"John\", ...\u003e\n```\n\nGet multiple random records:\n\n```ruby\nUser.random(count: 5)\n# =\u003e [#\u003cUser id: 1, ...\u003e, #\u003cUser id: 15, ...\u003e, ...]\n```\n\nChain with other ActiveRecord methods:\n\n```ruby\nUser.where(active: true).random(count: 3)\n# =\u003e [#\u003cUser id: 8, active: true, ...\u003e, ...]\n```\n\n### Advanced Usage\n\n#### Sampling Strategies\n\nRandomRails provides multiple sampling strategies:\n\n```ruby\n# Auto-select best strategy (default)\nUser.random(strategy: :auto)\n\n# Force TABLESAMPLE (PostgreSQL only)\nUser.random(strategy: :tablesample, precision: 1.0)\n\n# Use efficient offset-based sampling\nUser.random(strategy: :offset)\n\n# Fallback to ORDER BY RANDOM()\nUser.random(strategy: :order_by)\n```\n\n#### Configuration\n\nConfigure RandomRails globally:\n\n```ruby\n# config/initializers/random_rails.rb\nRandomRails.configure do |config|\n  config.default_strategy = :auto         # Default sampling strategy\n  config.tablesample_threshold = 10_000  # Use TABLESAMPLE for tables larger than this\n  config.cache_table_sizes = true         # Cache table size estimates\n  config.precision = 1.0                  # Default TABLESAMPLE precision\nend\n```\n\n#### Database-Specific Features\n\n##### PostgreSQL\n\n- Uses `TABLESAMPLE BERNOULLI` for large tables (\u003e 10k records by default)\n- Falls back to offset method for smaller tables\n- Fast table size estimation using `pg_class`\n\n##### MySQL\n\n- Uses efficient offset-based sampling\n- Table size estimation via `information_schema`\n- Fallback to `ORDER BY RAND()` when needed\n\n##### SQLite\n\n- Offset-based sampling for optimal performance\n- Graceful handling of table size estimation\n- Compatible with in-memory databases\n\n## Benchmarks\n\nRandomRails automatically selects the best strategy for your database and table size. The benchmarks above demonstrate real-world performance improvements across different table sizes, with RandomRails consistently delivering superior performance through intelligent strategy selection:\n\n- **Small tables**: Uses efficient offset-based sampling\n- **Large tables (PostgreSQL)**: Leverages `TABLESAMPLE BERNOULLI` for optimal performance\n- **All databases**: Falls back to optimized methods when needed\n\n## Development\n\nAfter checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.\n\nTo install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).\n\n## Contributing\n\nBug reports and pull requests are welcome on GitHub at https://github.com/the-rubies-way/random-rails. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/the-rubies-way/random-rails/blob/master/CODE_OF_CONDUCT.md).\n\n## License\n\nThe gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).\n\n## Code of Conduct\n\nEveryone interacting in the ActiveRecord::Random project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/the-rubies-way/random-rails/blob/master/CODE_OF_CONDUCT.md).\n\n## Thanks for your support!\n\n[\u003cimg width=\"100\" alt=\"RailsJazz\" src=\"https://avatars.githubusercontent.com/u/104008706?s=200\"\u003e](https://github.com/railsjazz)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fthe-rubies-way%2Frandom-rails","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fthe-rubies-way%2Frandom-rails","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fthe-rubies-way%2Frandom-rails/lists"}