有没有办法告诉 Rails,我的字符串可能不是某个特定的值?
我正在寻找类似下面的方法:
validates :string, :not => 'something'
谢谢 klump
有没有办法告诉 Rails,我的字符串可能不是某个特定的值?
我正在寻找类似下面的方法:
validates :string, :not => 'something'
谢谢 klump
以下两种方法都可以完成任务(点击链接查看详细文档):
Probably the best and fastest way, easy to extend for other words:
<a rel="noreferrer" href="http://apidock.com/rails/ActiveModel/Validations/HelperMethods/validates_exclusion_of">validates_exclusion_of</a> :string, :in => %w[something]
This has a benefit of using a regexp, so you can generalise easier:
<a rel="noreferrer" href="http://apidock.com/rails/ActiveModel/Validations/HelperMethods/validates_format_of">validates_format_of</a> :string, :without => /\A(something)\Z/
You can extend to other words with /\A(something|somethingelse|somemore)\Z/
This is the general case with which you can achieve any validation:
<a rel="noreferrer" href="http://apidock.com/rails/ActiveModel/Validations/ClassMethods/validate">validate</a> :cant_be_something
def cant_be_something
<a rel="noreferrer" href="http://apidock.com/rails/v3.0.0/ActiveModel/Errors/add">errors.add</a>(:string, "can't be something") if self.string == "something"
end
To get exactly the syntax you proposed (validates :string, :not => "something"
) you can use this code (a warning though, I discovered this while reading the master branch of the rails source and it should work, but it doesn't work on my ~ 3 months old install). Add this somewhere in your path:
class NotValidator < <a rel="noreferrer" href="http://apidock.com/rails/ActiveModel/EachValidator">ActiveModel::EachValidator</a>
def <a rel="noreferrer" href="http://apidock.com/rails/ActiveModel/EachValidator/validate_each">validate_each</a>(record, attribute, value)
record.errors[attribute] << "must not be #{options{:with}}" if value == options[:with]
end
end
validates_exclusion_of :string, :in => ["something", "something else"]
validates_format_of :string, :with => /\A(?!something)\Z/
validate :not_something
def not_something
errors.add(:string, "Can't be something") if string =~ /something/
end
\A
和\Z
可能是一个更安全的想法 - 很好的发现。 - Jakub Hampl