Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.