Alain wrote:
should be aware of changes to any of these fields by comparing the
params hash with the hash in memory.
Anyone can comment on this? I am just guessing…
Yes, I think it’d be useful for Active Record to track which
attributes in a model have changed, both allowing the user to
identify changed fields, and restricting DB updates to only those
changed fields.
I actually wrote a mod to implement this, but I don’t think I’ve
fully tested it. It adds a @changed_attributes hash to a model.
What held me up was also implementing a @changed_association hash
which allowed AR to not only automatically save the new records
in an object’s descended associates, but also any changed attribute
in those descendants. This would simplify controller code.
Here’s the code to get the flavour of what is required. Changed
lines marked with ‘N’.
module ActiveRecord
class Base
def initialize(attributes = nil)
@attributes = attributes_from_column_definition
N @changed_attributes = {}
@new_record = true
ensure_proper_type
self.attributes = attributes unless attributes.nil?
yield self if block_given?
end
def write_attribute(attr_name, value)
attr_name = attr_name.to_s
if (column = column_for_attribute(attr_name)) && column.number?
new_value = convert_number_column_value(value)
N if new_value != @attributes[attr_name]
N @changed_attributes[attr_name] = true
N @attributes[attr_name] = new_value
end
else
@attributes[attr_name] = value
end
end
private
N def attributes_with_quotes(include_primary_key = true, only_changed
= false)
attributes.inject({}) do |quoted, (name, value)|
if column = column_for_attribute(name)
N unless !include_primary_key && column.primary || only_changed
&& @changed_attributes[name]
quoted[name] = quote(value, column)
end
end
quoted
end
end
def update
N quoted_attributes = attributes_with_quotes(false,true)
connection.update(
"UPDATE #{self.class.table_name} " +
N "SET #{quoted_comma_pair_list(connection, quoted_attributes)} "
+
“WHERE #{self.class.primary_key} = #{quote(id)}”,
“#{self.class.name} Update”
N ) unless quoted_attributes.empty?
return true
end
end
end
–
We develop, watch us RoR, in numbers too big to ignore.