Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Rails Polymorphic Association Query

Rails Polymorphic Association Query

Example use case:

class User < ApplicationRecord
  belongs_to :authable, polymorphic: true, optional: true
end
 
class Google < ApplicationRecord
  has_one :user, as: :authable, dependent: :destroy, touch: true
end
 
class Facebook < ApplicationRecord
  has_one :user, as: :authable, dependent: :destroy, touch: true
end

Extended version:

class User < ApplicationRecord
  belongs_to :authable, polymorphic: true, optional: true
  
  scope :join_authable, lambda { |type|
    joins("JOIN #{type.table_name} ON #{type.table_name}.id = #{User.table_name}.authable_id AND #{User.table_name}.authable_type = '#{type.to_s}'")
  }
  scope :by_google_email, lambda { |email|
    where('oauth_googles.email = ?', email)
  }
  scope :by_facebook_identifier, lambda { |identifier|
    where('oauth_facebooks.identifier = ?', identifier)
  }
  
  def self.find_by_google_email(email)
    join_authable(Google).by_google_email(email).first
  end

  def self.find_by_facebook_identifier(identifier)
    join_authable(Facebook).by_facebook_identifier(identifier).first
  end
end

Usage:

user = User.find_by_google_email "yunusemredilber0@gmail.com" # <User#123123>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment