Reputation: 697
In our Rails 3.2.6 app, we have a model attribute named 'version' that is incremented at the database level whenever an instance is created or updated (via trigger). However, after we do a successful create or update, the new value set by the database is not being returned to our instance, unless we explicitly do an instance.reload.
Does anyone know of a way to have active record automatically reload the instance after persisting to the database?
In our Rails 3.2.6 app, we have a 3 tables that each have a 'version' column. Across all 3 tables, the 'version' integer column needs to be incremented during each insert and update, and the 'version' must never repeat.
Simple solution: we've created a version_sequence in postgres that all 3 tables share. We have a small trigger that updates the version column of any record from these tables with the nextval('version_sequence') value:
-- Resource Version Sequence
CREATE SEQUENCE resource_versions_seq;
-- Resource Version Trigger
CREATE FUNCTION update_resource_version() RETURNS trigger AS $update_resource_version$
BEGIN
NEW.version := nextval('resource_versions_seq');
RETURN NEW;
END;
$update_resource_version$ LANGUAGE plpgsql;
However, when we create, save, or update_attributes in active_record, the new 'version' value is not being reloaded after the record is persisted.
Upvotes: 4
Views: 2200
Reputation: 5239
How about using the after_save callback? In this callback you could fetch just that field and then set it on the model. Something like this:
class Thing < ActiveRecord::Base
after_save :refresh_version
def refresh_version
self.version = Thing.find(self.id).select(:version)
end
end
Upvotes: 3