I have a “user” model that “has_one” “membership” (active at a time). For auditing and data integrity reasons, I’d like it so that if the membership changes for a user, the old/current record (if existing) has an inactive/active flag swapped, and a new row is added for the new changed record. If there are no changes to the membership, I’d like to just ignore the update. I’ve tried implementing this with a “before_save” call-back on my user model, but have failed many times. Any help is greatly appreciated.
models:
class User < ActiveRecord::Base
has_one :membership, :dependent => :destroy
accepts_nested_attributes_for :membership, :allow_destroy => true
end
class Membership < ActiveRecord::Base
default_scope :conditions => {:active => 1}
belongs_to :user
end
Got it working. While it’s probably not the best implementation, all my tests are passing. Thanks for the input guys.
before_save :soft_delete_changed_membership def soft_delete_changed_membership if !membership.nil? then if !membership.new_record? && membership.trial_expire_at_changed? then Membership.update_all( "active = 0", [ "id = ?", self.membership.id ] ) trial_expire_at = self.membership.trial_expire_at self.membership = nil Membership.create!( :user_id => self.id, :trial_expire_at => trial_expire_at, :active => true ) self.reload end end end