Skip to content

Instantly share code, notes, and snippets.

@amkisko
Last active October 15, 2023 08:44
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 amkisko/f61fcd66a87710af713d8d717e45d534 to your computer and use it in GitHub Desktop.
Save amkisko/f61fcd66a87710af713d8d717e45d534 to your computer and use it in GitHub Desktop.
Rails application view record for using pure sql files as source of base query for the model
# AUTHOR: Andrei Makarov (github.com/amkisko)
class ApplicationViewRecord < ApplicationRecord
self.abstract_class = true
def self.attribute_names
@attribute_names ||= attribute_types.keys
end
def self.load_schema!
@columns_hash ||= {}
attributes_to_define_after_schema_loads.each do |name, (cast_type, default)|
cast_type = cast_type[type_for_attribute(name)] if Proc === cast_type
cast_type = connection.lookup_cast_type_from_column(type) if Symbol ===
cast_type
define_attribute(name, cast_type, default: default)
@columns_hash[name.to_s] = ActiveRecord::ConnectionAdapters::Column.new(
name.to_s,
default
)
end
end
def self.default_scope
from("(#{view_definition.gsub(/\s+/, " ").strip}) as #{table_name}")
end
def self.view_name
name.underscore.pluralize
end
def self.view_definition_path
Rails.root.join("db/views", "#{view_name}.sql")
end
def self.view_definition
File.read(view_definition_path)
end
def persisted?
true
end
def readonly?
true
end
end
select id as entry_id,
'FirstEntry' as entry_type,
some_created_at as created_at,
some_updated_at as updated_at
from first_entries
union
select id as entry_id,
'SecondEntry' as entry_type,
other_created_at as created_at,
other_updated_at as updated_at
from second_entries
# AUTHOR: Andrei Makarov (github.com/amkisko)
class SampleEntry < ApplicationViewRecord
belongs_to :entry, polymorphic: true
attribute :entry_id, :string, default: nil
attribute :entry_type, :string, default: nil
attribute :created_at, :datetime, default: nil
attribute :updated_at, :datetime, default: nil
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment