Class: ActiveRecord::View

Inherits:
Base
  • Object
show all
Defined in:
lib/active_record/view.rb

Overview

:nodoc:

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.based_on(model) ⇒ Object

Clones all applicable associations from model to this view and provides an instance method to_model that casts a view object to an object of the kind view is based on. This latter object may be missing attributes; to fill them in, call #reload.



19
20
21
22
23
24
25
26
27
# File 'lib/active_record/view.rb', line 19

def based_on(model)
  define_method("to_#{model.name.demodulize.underscore}") do
    becomes(model)
  end
  
  model.reflect_on_all_associations.each do |assoc|
    clone_association(model, assoc)
  end
end

.clone_association(model, *associations) ⇒ Object

Clone one or more associations from model to this view class.

NOTE: Currently only belongs_to, has_many (withouth :through), and has_and_belongs_to_many associations are supported.



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/active_record/view.rb', line 34

def clone_association(model, *associations)
  associations.each do |association|
    r = case association
        when String, Symbol
          model.reflect_on_association(association.to_sym)
        when ActiveRecord::Reflection::AssociationReflection
          association
        else
          raise ArgumentError, "Unrecognized association #{association.inspect}; must be a Symbol, String, or AssociationReflection."
        end
    case r.macro
    when :belongs_to
      if self.column_names.include?(r.primary_key_name.to_s)
        if !r.options[:foreign_type] || self.column_names.include?(r.options[:foreign_type])
          options = r.options.merge(
            :class_name => r.class_name,
            :foreign_key => r.primary_key_name
          )
          belongs_to r.name, options
        end
      end
    when :has_many
      ### TODO :through assocications
      options = r.options.merge(
        :class_name => r.class_name,
        :foreign_key => r.primary_key_name
      )
      has_many r.name, options
    when :has_and_belongs_to_many
      options = r.options.merge(
        :class_name => r.class_name,
        :foreign_key => r.primary_key_name,
        :association_foreign_key => r.association_foreign_key
      )
      has_and_belongs_to_many r.name, options
    when :has_one
      ### TODO
    end
  end
end

Instance Method Details

#readonly?Boolean

Returns:

  • (Boolean)


8
9
10
# File 'lib/active_record/view.rb', line 8

def readonly?
  true
end