Skip to content

Instantly share code, notes, and snippets.

@jimworm
Created July 20, 2012 07:51
Show Gist options
  • Save jimworm/3149393 to your computer and use it in GitHub Desktop.
Save jimworm/3149393 to your computer and use it in GitHub Desktop.
Enforce/prevent attribute change in Rails 3
class ChangeValidator < ActiveModel::EachValidator
# Enforce/prevent attribute change
#
# Example: Make attribute immutable once saved
# validates :attribute, change: false, on: :update
#
# Example: Force attribute change on every save
# validates :attribute, change: true
def initialize(options)
options[:change] = !(options[:with] === false)
super
end
def validate_each(record, attribute, value)
record.errors.add(attribute, "#{options[:change] ? 'must' : 'cannot'} be modified") unless record.public_send(:"#{attribute}_changed?") == options[:change]
end
end
@relativkreativ
Copy link

I don't know if this works in Rails 3 - however, I think in Rails 4

validates :attribute, change: false

causes the validation to NOT run, so you need to use

validates :attribute, change: { with: false }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment