Skip to content

Instantly share code, notes, and snippets.

@yunusemredilber
Created September 14, 2020 12:33
Show Gist options
  • Save yunusemredilber/129590459adb3027be898eff6ab932c6 to your computer and use it in GitHub Desktop.
Save yunusemredilber/129590459adb3027be898eff6ab932c6 to your computer and use it in GitHub Desktop.
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 "[email protected]" # <User#123123>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment