module ConstantRecord::Associations
Hooks to integrate ActiveRecord associations with constant records.
Public Class Methods
included(base)
click to toggle source
# File lib/constant_record.rb, line 148 def self.included(base) base.extend self # support "include" end
Public Instance Methods
has_many(other_table, options={})
click to toggle source
Override the default ActiveRecord.has_many(:through) that does in-database joins, with a method that makes two fetches. It's the only reliable way to traverse databases. Hopefully one (or both) of these tables are in-memory ConstantRecords so that we're not making real DB calls.
Calls superclass method
# File lib/constant_record.rb, line 158 def has_many(other_table, options={}) super other_table, options.dup # make AR happy # Redefine association method in the class if join_tab = options[:through] foreign_key = options[:foreign_key] || other_table.to_s.singularize.foreign_key prime_key = options[:primary_key] || primary_key class_name = options[:class_name] || other_table.to_s.classify join_key = table_name.to_s.singularize.foreign_key define_method other_table do join_class = join_tab.to_s.classify.constantize ids = join_class.where(join_key => send(prime_key)).pluck(foreign_key) return [] if ids.empty? class_name.constantize.where(id: ids) end end end