Ruby on rails 如何在rails';s模型
我知道ActiveRecord提供了一些宏,如Ruby on rails 如何在rails';s模型,ruby-on-rails,Ruby On Rails,我知道ActiveRecord提供了一些宏,如验证的唯一性验证的大小 对用户输入进行一些验证。但我想知道是否有可能提供 一些类似回调的验证方法将用作模型级别的简化验证方法。例如 我想检查输入字符串只包含从“a”到“h”的字母,有趣吗?但这种情况时有发生 提供了一个很好的示例,说明如何创建自己的自定义验证器。如果您使用的是Rails 3,您可以这样做: class Foo < ActiveRecord::Base validate :from_a_to_h # Use the na
验证的唯一性验证的大小
对用户输入进行一些验证。但我想知道是否有可能提供
一些类似回调的验证方法将用作模型级别的简化验证方法。例如
我想检查输入字符串只包含从“a”到“h”的字母,有趣吗?但这种情况时有发生 提供了一个很好的示例,说明如何创建自己的自定义验证器。如果您使用的是Rails 3,您可以这样做:
class Foo < ActiveRecord::Base
validate :from_a_to_h
# Use the name of your attribute in place of :input and input.
def from_a_to_h
errors.add(:input, "must contain only letters from a to h") if input =~ /[i-Z]+/
end
end
class Foo
您可以使用以下工具创建自定义函数:
validate :custom_function
def custom_function
...
end
还可以使用正则表达式验证字符串。对于您的示例,我将使用:
validates_format_of :attribute, :with => /^[a-h]+$/