views:

473

answers:

3

Hey folks,

I have a database table with a certain field which should be impossible to update once it has been inserted to the database. How do I tell my model that it shouldn't allow updating of a certain field?

Best Regards, x3ro

A: 

My rails is rusty, but I think that something like the following would do the trick:

def foo= (val)
    raise DontDoThatException.new
end
Thom Smith
This also prevents creating the object in the first place.
x3ro
+5  A: 

You want to use attr_readonly.

From the docs: "Attributes listed as readonly can be set for a new record, but will be ignored in database updates afterwards"

class Customer < ActiveRecord::Base
    attr_readonly :your_field_name
end
Mike Buckbee
A: 

And that field is always and by definition "correct" (i.e. an accurate representation of reality) at the time of insertion ?

No user ever makes a mistake when entering that field for the first (and in your scheme : only) time ?

Erwin Smout
Actually the user doesn't enter it at all, it's set by the controller. What I want to prevent is that someone modifies it using an altered post-request.
x3ro