diff options
Diffstat (limited to 'activerecord/lib/active_record/persistence.rb')
-rw-r--r-- | activerecord/lib/active_record/persistence.rb | 39 |
1 files changed, 26 insertions, 13 deletions
diff --git a/activerecord/lib/active_record/persistence.rb b/activerecord/lib/active_record/persistence.rb index 8e749772a1..eed49e17b1 100644 --- a/activerecord/lib/active_record/persistence.rb +++ b/activerecord/lib/active_record/persistence.rb @@ -72,11 +72,9 @@ module ActiveRecord # +save+ returns +false+. See ActiveRecord::Callbacks for further # details. def save(*) - begin - create_or_update - rescue ActiveRecord::RecordInvalid - false - end + create_or_update + rescue ActiveRecord::RecordInvalid + false end # Saves the model. @@ -155,7 +153,18 @@ module ActiveRecord became.instance_variable_set("@new_record", new_record?) became.instance_variable_set("@destroyed", destroyed?) became.instance_variable_set("@errors", errors) - became.public_send("#{klass.inheritance_column}=", klass.name) unless self.class.descends_from_active_record? + became + end + + # Wrapper around +becomes+ that also changes the instance's sti column value. + # This is especially useful if you want to persist the changed class in your + # database. + # + # Note: The old instance's sti column value will be changed too, as both objects + # share the same set of attributes. + def becomes!(klass) + became = becomes(klass) + became.public_send("#{klass.inheritance_column}=", klass.sti_name) unless self.class.descends_from_active_record? became end @@ -171,7 +180,7 @@ module ActiveRecord name = name.to_s verify_readonly_attribute(name) send("#{name}=", value) - save(:validate => false) + save(validate: false) end # Updates the attributes of the model from the passed-in hash and saves the @@ -226,8 +235,8 @@ module ActiveRecord updated_count = self.class.where(self.class.primary_key => id).update_all(attributes) - attributes.each do |k,v| - raw_write_attribute(k,v) + attributes.each do |k, v| + raw_write_attribute(k, v) end updated_count == 1 @@ -379,10 +388,14 @@ module ActiveRecord # Returns the number of affected rows. def update(attribute_names = @attributes.keys) attributes_with_values = arel_attributes_with_values_for_update(attribute_names) - return 0 if attributes_with_values.empty? - klass = self.class - stmt = klass.unscoped.where(klass.arel_table[klass.primary_key].eq(id)).arel.compile_update(attributes_with_values) - klass.connection.update stmt + + if attributes_with_values.empty? + 0 + else + klass = self.class + stmt = klass.unscoped.where(klass.arel_table[klass.primary_key].eq(id)).arel.compile_update(attributes_with_values) + klass.connection.update stmt + end end # Creates a record with values matching those of the instance attributes |