Module: ChildInstanceMethods

Includes:
InstanceMethods
Defined in:
lib/citier/child_instance_methods.rb

Instance Method Summary collapse

Methods included from InstanceMethods

#delete, #destroy, #updatetype

Instance Method Details

#saveObject



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/citier/child_instance_methods.rb', line 3

def save

  #get the attributes of the class which are inherited from it's parent.
  attributes_for_parent = self.attributes.reject{|key,value| !self.class.superclass.column_names.include?(key) }

  # Get the attributes of the class which are unique to this class and not inherited.
  attributes_for_current = self.attributes.reject{|key,value| self.class.superclass.column_names.include?(key) }

  citier_debug("Attributes for #{self.class.to_s}: #{attributes_for_current.inspect.to_s}")

  #create a new instance of the superclass, passing the inherited attributes.
  parent = self.class.superclass.new(attributes_for_parent)
  parent.id = self.id

  parent.is_new_record(new_record?)

  parent_saved = parent.save
  self.id = parent.id

  if(parent_saved==false)
    # Couldn't save parent class
    # TODO: Handle situation where parent class could not be saved
    citier_debug("Class (#{self.class.superclass.to_s}) could not be saved")
  end

  # If there are attributes for the current class (unique & not inherited) 
  # and parent(s) saved successfully, save current model
  if(!attributes_for_current.empty? && parent_saved)
    current = self.class::Writable.new(attributes_for_current)
    current.id = self.id
    current.is_new_record(new_record?)
    current_saved = current.save
    
    # This is no longer a new record
    is_new_record(false)

    if(!current_saved)
      citier_debug("Class (#{self.class.superclass.to_s}) could not be saved")
    end
  end

  # Update root class with this 'type'
  if parent_saved && current_saved
    sql = "UPDATE #{self.class.root_class.table_name} SET #{self.class.inheritance_column} = '#{self.class.to_s}' WHERE id = #{self.id}"
    citier_debug("SQL : #{sql}")
    self.connection.execute(sql)
  end
  return parent_saved && current_saved
end

#save!Object

Raises:

  • (ActiveRecord::RecordInvalid)


53
54
55
56
# File 'lib/citier/child_instance_methods.rb', line 53

def save!
  raise ActiveRecord::RecordInvalid.new(self) unless self.valid?
  self.save
end