嗨
有什么方法可以告诉 Rails 我的字符串可能不是“某物”?
我正在寻找类似的东西
validates :string, :not => 'something'
谢谢
团块
最佳答案
其中任何一个都可以完成工作(单击文档的方法):
validates_exclusion_of :string, :in => %w[something]
validates_format_of :string, :without => /\A(something)\Z/
您可以使用
/\A(something|somethingelse|somemore)\Z/
扩展到其他词validate :cant_be_something
def cant_be_something
errors.add(:string, "can't be something") if self.string == "something"
end
validates :string, :not => "something"
),您可以使用此代码(尽管警告,我在阅读 rails 源代码的 master 分支时发现了这一点,它应该可以工作,但在我的 ~ 3 个月内不起作用旧安装)。将此添加到您的路径中的某处:class NotValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
record.errors[attribute] << "must not be #{options{:with}}" if value == options[:with]
end
end
关于ruby-on-rails - rails 3 验证字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4933403/