0
我想驗證該用戶名不是下列之一。 ["admin", "moderator", "mod", "administrator"]
。數據庫級別的模型屬性數據驗證
我確認這些名稱不允許在模型級使用自定義驗證器。
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
我想知道如果我能在數據庫級驗證這個問題,以及(可能使用遷移文件?)。這可以完成上述特定情況嗎?
這種做法似乎是由Rails guide以及
鼓勵它可能是在數據庫級別使用一些限制是個好主意。另外,數據庫級別的驗證可以安全地處理某些事情 (例如高度使用表中的唯一性),否則難以實施。
有不嘗試這個自己,但這可能有所幫助: http://stackoverflow.com/questions/4664520/how-do-i-add-a-check-constraint-in-a-rails-migration – donsteffenski
你使用什麼數據庫? –
dev上的sqlite,prod上的postgresql –