module ActiveRecord::Chemistry::Representable::Relation

Public Instance Methods

representable(name, scope = nil, options = {}) click to toggle source
# File lib/activerecord/chemistry/representable/relation.rb, line 41
def representable(name, scope = nil, options = {})
  reflections = has_many(name, scope, options.merge(dependent: :destroy))
  cattr_reader(:representable_reflection) { reflections.stringify_keys[name.to_s] }
end
represents(name, scope = nil, options = {}) click to toggle source
# File lib/activerecord/chemistry/representable/relation.rb, line 14
def represents(name, scope = nil, options = {})
  if Hash === scope
    options = scope
    scope = nil
  end
  reflections = belongs_to(name, scope, options)
  default_scope -> { includes(name) }
  validate :representable_must_be_valid
  
  before_validation :find_by_or_keep_representable, on: :create
  before_validation :update_or_instantiate_representable, on: :update

  after_destroy do
    representing.destroy if representing && representing.send(representing_model.representable_reflection.name).count == 0 && !representing.destroyed?
  end

  cattr_reader(:representing_reflection) { reflections.stringify_keys[name.to_s] }
  cattr_reader(:representing_model) { (options[:class_name] || name.to_s.camelize).constantize }
  class_eval "def #{name}; super || build_#{name}(representing_model.representable_reflection.name => [self]); end"
  alias_method :representing, name
  alias_method :representing=, "#{name}=".to_sym
  include Representable::InstanceMethods
  singleton_class.module_eval do
    include Representable::ClassMethods
  end
end