Reputation: 23268
I want to add a validation to the model to check that a field (string) could be set to something only it's original value is nil.
How can I do this?
Actually two subquestions are:
Upvotes: 1
Views: 305
Reputation: 4171
This seems like a custom job. Say you have a field named field
.
validate :no_modifications_on_field
def no_modifications_on_field
if field_changed? && !field_was.nil?
errors.add(:field, 'Once you set a field, you can never change it!')
end
end
field_changed?
and field_was
are ActiveModel::Dirty
helpers that get generated for every field. You can also access all changed attributes through changed_attributes
.
Upvotes: 3