at_most: ActiveRecord limiting in Rails
This post is out of date
This post has been migrated from my old blog. It may have broken links, or missing content.
tl;dr: at_most
is a Ruby gem for limiting the number of AR model instances in your Rails apps
I’ve found that if I’m repeating a use-case or functionality over multiple apps, it’s probably worth extracting into a reusable gem. So in that vein, I’ve released at_most, an easy way to limit your ActiveRecord model instances.
The primary function I’ve been using this for is limiting the number of users for an app. If you’re using something like ActiveAdmin for managing your models, it’s nice to limit the number of AdminUsers
for safety’s sake.
It’s really that simple. We can test this functionality by creating five users, and then attempting to create a sixth:
It’s important to note that this is a validation error — we can override this with our own custom error message fairly easily.
We can also use i18n to set an error message at a per model and global level:
This was a good chance for me to dig into how validations work a bit, and understand the proper way to add to them. As always, PRs and tickets are appreciated.
You can find at_most
on Github here.