Created
July 20, 2012 07:51
-
-
Save jimworm/3149393 to your computer and use it in GitHub Desktop.
Enforce/prevent attribute change in Rails 3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I don't know if this works in Rails 3 - however, I think in Rails 4
causes the validation to NOT run, so you need to use