Module: ActiveRecord::Defaults::InstanceMethods

Defined in:
lib/active_record/defaults.rb

Instance Method Summary collapse

Instance Method Details

#apply_default_attribute_values(attributes) ⇒ Object


89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/active_record/defaults.rb', line 89

def apply_default_attribute_values(attributes)
  attribute_keys = (attributes || {}).keys.map!(&:to_s)
  
  if attribute_defaults = self.class.read_inheritable_attribute(:attribute_defaults)
    attribute_defaults.each do |default|
      next if attribute_keys.include?(default.attribute)
      
      # Ignore a default value for association_id if association has been specified
      reflection = self.class.reflections[default.attribute.to_sym]
      if reflection and reflection.macro == :belongs_to and attribute_keys.include?(reflection.primary_key_name)
        next
      end
      
      # Ignore a default value for association if association_id has been specified
      reflection = self.class.reflections.values.find { |r| r.respond_to?(:primary_key_name) && r.primary_key_name == default.attribute }
      if reflection and reflection.macro == :belongs_to and attribute_keys.include?(reflection.name.to_s)
        next
      end
      
      send("#{default.attribute}=", default.value(self))
    end
  end
end

#initialize_with_defaults(attributes = nil) {|_self| ... } ⇒ Object

Yields:

  • (_self)

Yield Parameters:


83
84
85
86
87
# File 'lib/active_record/defaults.rb', line 83

def initialize_with_defaults(attributes = nil)
  initialize_without_defaults(attributes)
  apply_default_attribute_values(attributes)
  yield self if block_given?
end