Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a field to read-only in Rails after it's created

I'd like to protect a user-generated entry in a field after its initial creation.

I'm asking the user for a unique name when they set up a project, and I want to stop that being changeable after the creation.

Is there a way to do this in Rails? Can I set it as attr_accessible at first then switch it to to attr_protected?

Cheers

like image 542
Les Avatar asked Sep 26 '10 14:09

Les


1 Answers

You can add custom validation method to your model:

# Project model
validate :forbid_changing_name, on: :update

private

def forbid_changing_name
  errors.add :name, "can not be changed!" if self.name_changed?
end
like image 98
klew Avatar answered Sep 24 '22 03:09

klew