Created
January 26, 2016 18:06
-
-
Save rsierra/78c650edeea245a35e0e to your computer and use it in GitHub Desktop.
RoR: Lock values validation
This file contains 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
en: | |
errors: | |
messages: | |
lock: can't be changed |
This file contains 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
# 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 |
This file contains 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 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