I set out to solve a problem we have, where under certain circumstances; we may need to make an attribute or relationship immutable, that is once the attribute is written it is written forever. attr_readonly wasn’t appropriate, as that didn’t work for relationships, so I tried to prove the concept here:
This shows my tests, an example implementation (that ideally I would move to a module) — I’m not sure if this is an acceptable way to overload a relationship setter, I have expanded the test to now read http://pastie.org/562417 which may be overkill, but helped me understand how customer_id relates to customer as an attribute as against a relationship, but I’d be more than happy to be corrected!
I haven’t tried it, but I think
update_attribute(:customer_id => 1)will break in some cases. Also, I really don’t like the idea of overriding attribute setters.A better (IMHO) approach would be to override ‘before_update’ and take a not of it if anything was changed. You can do that using the Dirty module. Check out this:
I haven’t tested this, but it would go something of the lines of:
Of course, you’ll have a better idea on how to handle IMMUTABLE. If you put this in a Module, the before_save has to be in the
Module#includedhook