Skip to content

Instantly share code, notes, and snippets.

@rsierra
Created January 26, 2016 18:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rsierra/78c650edeea245a35e0e to your computer and use it in GitHub Desktop.
Save rsierra/78c650edeea245a35e0e to your computer and use it in GitHub Desktop.
RoR: Lock values validation
en:
errors:
messages:
lock: can't be changed
# app/validators/lock_validator.rb
class LockValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
lock_values = options[:values] || []
changed = record.send("#{attribute}_changed?")
value_was = record.send("#{attribute}_was")
if changed && lock_values.include?(value_was)
record.errors.add(attribute.to_sym, :lock)
end
end
end
class Page < ActiveRecord::Base
KINDS = {
home: 'home',
about_us: 'about-us'
}.freeze
validates :uid, lock: { values: Sample::KINDS.values }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment