Skip to content

Instantly share code, notes, and snippets.

@blairanderson
Created August 20, 2019 16:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blairanderson/9344b05099487209a384e865462b2d1e to your computer and use it in GitHub Desktop.
Save blairanderson/9344b05099487209a384e865462b2d1e to your computer and use it in GitHub Desktop.
rails query email by domain

A simple way to add querying by email

# frozen_string_literal: true

module DomainQuery
  extend ActiveSupport::Concern

  class_methods do
    def by_email(domain=nil)
      raise(ArgumentError.new("Missing domain! should look like Model.by_email('gmail.com') if domain.empty?
      self.where("lower(substring(email from '@(.*)$')) = ?", domain)
    end
  end
end

# include the extension
ActiveRecord::Base.send(:include, DomainQuery)

Then you can do things like Model.by_email('gmail.com')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment