Skip to content

Instantly share code, notes, and snippets.

@pedrocarmona
Created March 16, 2021 19:45
Show Gist options
  • Save pedrocarmona/c5d0065baf5a6263e9630abc5c71ffe1 to your computer and use it in GitHub Desktop.
Save pedrocarmona/c5d0065baf5a6263e9630abc5c71ffe1 to your computer and use it in GitHub Desktop.
Polymorphic lookup - collection
class SomethingLookup < ApplicationRecord
self.table_name = 'something_lookups'
belongs_to :something, polymorphic: true
def self.load_schema!
# rubocop:disable Naming/MemoizedInstanceVariableName
@columns_hash ||= {}
# rubocop:enable Naming/MemoizedInstanceVariableName
end
def self.default_scope
from(default_from)
end
def inspect
inspection = attributes.map { |name, value| "#{name}: #{value}" }.compact.join(', ')
"#<#{self.class} #{inspection}>"
end
def readonly?
true
end
def self.default_from
<<~SQL
(
SELECT concat('a_', id) as id, 'A' as something_type, id as something_id, created_at, updated_at
FROM as
UNION ALL
SELECT concat('b_', id) as id, 'B' as something_type, id as something_id, created_at, updated_at
FROM bs
) #{table_name}
SQL
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment