I was browsing through the Rails Docs, looking for a better way to do
updates.
When you use update_attributes, it saves all the attributes from the
object. I have some objects with very large text fields which means a
lot data going forth and back.
I was looking for a cleaner way. I created a wrapper for the update_all
method, which uses straight sql to do updates. So now, I can do
user.update_attributes_with_sql(:some_field=>some_value), like I would
with update_attributes, only it updates only the fields that I want.
Am I reinventing the wheel here? I couldn’t find any function to this in
AR.
I extended ActiveRecord with this:
def update_attributes_with_sql(attrs) # allows you to update
individual columns without saving the whole record (also much faster)
self.class.update_with_sql(id, attrs)
self.attributes = attrs
end
def self.update_with_sql(id, attrs)
conditions = id.is_a?(Array) ? "id IN (#{id.join(', ')})" :
“id=#{id}”
update_all sanitize_sql_hash_for_set(attrs), conditions
end
def self.sanitize_sql_hash_for_set(attrs)
# just need to replace the join with ', 'instead of AND
conditions = attrs.map do |attr, value|
"#{table_name}.#{connection.quote_column_name(attr)}
#{attribute_condition(value)}"
end.join(’, ')
replace_bind_variables(conditions, attrs.values)
end