Jeff
Jeff

Reputation: 103

Is it possible to make an ActiveRecord model in RoR write-once and lock?

I'm trying to figure out how to save an active record instance to the database and then lock it so that you can't write to it anymore (updates or saves), but you can still read from it.

I'd like to be able to do it upon creation in the model itself.

Upvotes: 0

Views: 171

Answers (1)

Emily
Emily

Reputation: 18193

Rather than overwriting the save method, I'd recommend you create a before_update hook that always returns false. From the callback documentation:

If a before_* callback returns false, all the later callbacks and the associated action are cancelled

A before_update callback will be run only when attempting to save an already-existing record. When it's originally created, it will run before_create instead. With the hook, you can be sure it will be called no matter what method is used to save the record. When you overwrite the existing save method, you'll have to make sure that save!, update_attributes, etc. are all overwritten as well.

Upvotes: 2

Related Questions