One of my models has a column that is updated very frequently from a
separate process, so it is important that when a record is saved in
rails, this column should be left alone. In the update method of the
controller I have:
params[:my_model] doesn’t have a reference to the column I’m talking
about, however, the UPDATE statement produced by update_attributes will
still assign a value to this column.
Even though its unlikely, if the separate process updates the record in
the time betweent the find, and the update, then the new value will be
lost. Is there a way to prevent this from happening?
about, however, the UPDATE statement produced by update_attributes will
still assign a value to this column.
Even though its unlikely, if the separate process updates the record in
the time betweent the find, and the update, then the new value will be
lost. Is there a way to prevent this from happening?
One option, not very clean and elegant, and probably prone to
deadlocks if you update several rows during a transaction, is locking
the row & reading its’ current value from a before_save callback.
E.g.:
def before_save
unless self.new_record?
current = self.class.find(self.id, :lock => true) # “select for
update”, locking row
write_attribute(:some_attribute, current.some_attribute)
end
end
def before_save
unless self.new_record?
current = self.class.find(self.id, :lock => true) # “select for
update”, locking row
write_attribute(:some_attribute, current.some_attribute)
end
end
about, however, the UPDATE statement produced by update_attributes
will
still assign a value to this column.
Even though its unlikely, if the separate process updates the
record in
the time betweent the find, and the update, then the new value will be
lost. Is there a way to prevent this from happening?
This has the same problem, both “update_attribute” and
“update_attributes” call the “save” method, which in turn, calls the
“update” method. This is whats setting the values of all the columns in
the table.
Yes, both attr_protected and attr_accessible only allow/prevent values
being assigned at the Rails level, the underlying SQL UPDATE that is
executed is still updating the values of all the columns.
Even though its unlikely, if the separate process updates the record in
the time betweent the find, and the update, then the new value will be
lost. Is there a way to prevent this from happening?