Module: SaveWhatsValid

Extended by:
ActiveSupport::Concern
Defined in:
lib/save_whats_valid.rb,
lib/save_whats_valid/version.rb

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

VERSION =
"0.0.1"

Instance Method Summary collapse

Instance Method Details

#update_attributes(attributes) ⇒ Object



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
# File 'lib/save_whats_valid.rb', line 11

def update_attributes(attributes)
  saved_successfully = super(attributes)
  
  if self.class.save_whats_valid_attributes.present?

    # load a copy of the listing.
    copy = self.class.find(id)
  
    unless saved_successfully

      fields = self.class.save_whats_valid_attributes.map(&:to_s)
      
      self.changed.each do |changed_field|

        # if this is one of the fields we allow to be updated even when the object itself is invalid...
        if fields.include? changed_field
         
          # unless this field is one of the fields with an error...
          unless self.errors.messages.keys.map(&:to_s).include? changed_field

            # otherwise, just copy over the field we want to save.
            copy.send("#{changed_field}=", self.send(changed_field))
         
            # save it regardless of the state of the object.
            copy.save(validate: false)

          end
       
        end

      end
    
    end
    
  end
  
  return saved_successfully
end