Monday, June 9, 2008

No, you can't delete accounts!

In many cases, bank managers ask you to keep an account information even it is closed or removed. Usually we keep the record in database but mark it by a flag column like 'delete_at' or 'status'.

To provent the false deletion, a method is registered to callback before_destroy.


class Account < ActiveRecord::BASE
...

protected

def before_destroy
update_attribute(:delete_at, Time.now) and return false
end
end


Notice that return false is very important. It halts the execution of the further deletion action.

Also notice that delete and delete_all ActiveRecord model methods will bypass the before_destroy callback methods.

for example:


>>account=Account.find 1
>>account.destroy #this will trigger the callback

>>account=Account.find 1
>>Account.delete(account) #this will not trigger the callback

No comments: