I want to validate that username is not one of the following. ["admin", "moderator", "mod", "administrator"]
.
I do validate that these names are not allowed at the model level using custom validator.
class User < ActiveRecord::Base
...
validate :username_should_not_be
def username_should_not_be
not_allowed = ["admin", "moderator", "mod", "administrator"]
if not_allowed.include?(username.downcase)
error.add(:username, "is not allowed.")
end
end
...
end
I'd like to know if I can validate this at database level as well (maybe using migration file?). Can this be done for the particular case above?
This practise seems to be encouraged by Rails guide as well
it may be a good idea to use some constraints at the database level. Additionally, database-level validations can safely handle some things (such as uniqueness in heavily-used tables) that can be difficult to implement otherwise.