Nikita Hismatov
Nikita Hismatov

Reputation: 1656

Rails: generate a key and make it readonly

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

Answers (3)

Marian Theisen
Marian Theisen

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

Arkan
Arkan

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

plasticide
plasticide

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

Related Questions