Reputation: 1656
I got an Order
model.
It should have a random generated key
field (and I need to save it to database).
Once it is created, the key should be readonly.
How can I do it?
PS:
I created @key instance variable in after_initialize
, but it does not want to be stored in the database. What am I doing wrong?
Upvotes: 0
Views: 120
Reputation: 6353
you should use the before_create
callback to generate the key. then overwrite the key=
accessor to prevent overwriting of this key:
def key= value
raise "not allowed, you fool!"
end
Upvotes: 0
Reputation: 6236
You can use callbacks and ActiveRecord::Dirty to do what your want.
Create a column in your database such as key which will be a String.
Then in your model add this.
before_save :set_key_if_needed
def set_key_if_needed
if self.persisted?
self.errors.add(:key, 'key cannot be changed') if self.key.changed?
else
self.key = "Your key randomly generated"
end
end
If persisted?(if the object has been saved to database already) you check if the key has changed, and if so you prevent the validation to succeed. Otherwise you just generate your key.
Upvotes: 0
Reputation: 1240
make sure your key
field is attr_reader and that you have a migration that adds the key field to your model's database table.
Upvotes: 1