Skip to content

Instantly share code, notes, and snippets.

@pesta
Created October 18, 2018 18:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pesta/306757c425abb77aed390f660437330e to your computer and use it in GitHub Desktop.
Save pesta/306757c425abb77aed390f660437330e to your computer and use it in GitHub Desktop.
class ImmutableValidator < ActiveModel::EachValidator
def validate_each(record, attribute, _value)
return unless record.persisted?
association_key = if record.attribute_names.include?(attribute.to_s)
attribute
else
record.reflections[attribute].foreign_key
end
record.errors[attribute] << 'can\'t be changed' if record.send("#{association_key}_changed?")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment