ruby
36 lines · 8 steps
Enforcing scoped uniqueness in Rails
A Membership model normalizes email and guarantees one member per organization, backed by a matching database index.
Explained by
highlit
1class Membership < ApplicationRecord
2 belongs_to :organization
3 belongs_to :user
4
5 before_validation :normalize_email
6
7 validates :email, presence: true
8 validates :email,
9 uniqueness: {
10 scope: :organization_id,
11 case_sensitive: false,
12 message: "is already a member of this organization"
13 }
14
15 validates :role, inclusion: { in: %w[owner admin member guest] }
16
17 scope :for_organization, ->(org) { where(organization: org) }
18
19 private
20
21 def normalize_email
22 self.email = email.to_s.strip.downcase.presence
23 end
24end
25
26class AddMembershipsUniqueIndex < ActiveRecord::Migration[7.1]
27 disable_ddl_transaction!
28
29 def change
30 add_index :memberships,
31 "organization_id, lower(email)",
32 unique: true,
33 name: "index_memberships_on_org_and_lower_email",
34 algorithm: :concurrently
35 end
36end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Normalizing input before validation makes case-insensitive uniqueness reliable and predictable.
- 2Model-level uniqueness validations should always be backed by a matching database unique index to close race conditions.
- 3A functional index on lower(email) lets the database enforce the same case-insensitive rule the model expresses.
Related explainers
ruby
class WebhookSignatureConstraint def initialize(provider) @provider = provider end
Verifying webhook signatures with Rails routing constraints
routing constraints
hmac
webhooks
Advanced
7 steps
ruby
module UniqueJob extend ActiveSupport::Concern class_methods do
Deduplicating Active Job enqueues in Rails
concurrency
idempotency
caching
Advanced
9 steps
ruby
class OrderMailerPreview < ActionMailer::Preview def confirmation OrderMailer.confirmation(sample_order) end
Previewing Rails mailers with sample data
mailer-previews
test-fixtures
in-memory-objects
Beginner
6 steps
ruby
def render_table(rows) return "(no data)" if rows.empty? columns = rows.flat_map(&:keys).uniq
Rendering an ASCII table in Ruby
text-formatting
column-alignment
recursion
Intermediate
8 steps
ruby
class ApplicationController < ActionController::Base ALLOWED_REDIRECT_HOSTS = [nil, ENV.fetch("APP_HOST", "app.example.com")].freeze def store_return_to(location = request.fullpath)
Safe post-login redirects in Rails
open-redirect
session
authentication
Intermediate
9 steps
ruby
require 'set' class DirectoryWatcher def initialize(path, pattern: '**/*', interval: 1.0)
Polling for file changes in Ruby
polling
filesystem
diffing
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/enforcing-scoped-uniqueness-in-rails-explained-ruby-9288/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.