Instance Public methods
attribute_method?(attribute)Link

Returns true if attribute is an attribute method, false otherwise.

class Person
include ActiveModel::Validations attr_accessor :name
end User.attribute_method?(:name) # => true
User.attribute_method?(:age) # => false

Source: show | on GitHub

clear_validators!()Link

Clears all of the validators and validations.

Note that this will clear anything that is being used to validate the model for both the validates_with and validate methods. It clears the validators that are created with an invocation of validates_with and the callbacks that are set by an invocation of validate.

class Person
include ActiveModel::Validations validates_with MyValidator
validates_with OtherValidator, on: :create
validates_with StrictValidator, strict: true
validate :cannot_be_robot def cannot_be_robot
errors.add(:base, 'A person cannot be a robot') if person_is_robot
end
end Person.validators
# => [
# #<MyValidator:0x007fbff403e808 @options={}>,
# #<OtherValidator:0x007fbff403d930 @options={on: :create}>,
# #<StrictValidator:0x007fbff3204a30 @options={strict:true}>
# ]

If one runs Person.clear_validators! and then checks to see what validators this class has, you would obtain:

Person.validators # => []

Also, the callback set by +validate :cannot_be_robot+ will be erased so that:

Person._validate_callbacks.empty?  # => true

Source: show | on GitHub

validate(*args, &block)Link

Adds a validation method or block to the class. This is useful when overriding the validate instance method becomes too unwieldy and you’re looking for more descriptive declaration of your validations.

This can be done with a symbol pointing to a method:

class Comment
include ActiveModel::Validations validate :must_be_friends def must_be_friends
errors.add(:base, 'Must be friends to leave a comment') unless commenter.friend_of?(commentee)
end
end

With a block which is passed with the current record to be validated:

class Comment
include ActiveModel::Validations validate do |comment|
comment.must_be_friends
end def must_be_friends
errors.add(:base, 'Must be friends to leave a comment') unless commenter.friend_of?(commentee)
end
end

Or with a block where self points to the current record to be validated:

class Comment
include ActiveModel::Validations validate do
errors.add(:base, 'Must be friends to leave a comment') unless commenter.friend_of?(commentee)
end
end

Options:

  • :on - Specifies the context where this validation is active (e.g. on: :create or on: :custom_validation_context)

  • :allow_nil - Skip validation if attribute is nil.

  • :allow_blank - Skip validation if attribute is blank.

  • :if - Specifies a method, proc or string to call to determine if the validation should occur (e.g. if: :allow_validation, or if: Proc.new { |user| user.signup_step > 2 }). The method, proc or string should return or evaluate to atrue or false value.

  • :unless - Specifies a method, proc or string to call to determine if the validation should not occur (e.g. unless: :skip_validation, or unless: Proc.new { |user| user.signup_step <= 2 }). The method, proc or string should return or evaluate to a true or false value.

Source: show | on GitHub

validates(*attributes)Link

This method is a shortcut to all default validators and any custom validator classes ending in ‘Validator’. Note that Rails default validators can be overridden inside specific classes by creating custom validator classes in their place such as PresenceValidator.

Examples of using the default rails validators:

validates :terms, acceptance: true
validates :password, confirmation: true
validates :username, exclusion: { in: %w(admin superuser) }
validates :email, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, on: :create }
validates :age, inclusion: { in: 0..9 }
validates :first_name, length: { maximum: 30 }
validates :age, numericality: true
validates :username, presence: true
validates :username, uniqueness: true

The power of the validates method comes when using custom validators and default validators in one call for a given attribute.

class EmailValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
record.errors.add attribute, (options[:message] || "is not an email") unless
value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/
end
end class Person
include ActiveModel::Validations
attr_accessor :name, :email validates :name, presence: true, uniqueness: true, length: { maximum: 100 }
validates :email, presence: true, email: true
end

Validator classes may also exist within the class being validated allowing custom modules of validators to be included as needed.

class Film
include ActiveModel::Validations class TitleValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
record.errors.add attribute, "must start with 'the'" unless value =~ /\Athe/
end
end validates :name, title: true
end

Additionally validator classes may be in another namespace and still used within any class.

validates :name, :'film/title' => true

The validators hash can also handle regular expressions, ranges, arrays and strings in shortcut form.

validates :email, format: /@/
validates :gender, inclusion: %w(male female)
validates :password, length: 6..20

When using shortcut form, ranges and arrays are passed to your validator’s initializer as options[:in] while other types including regular expressions and strings are passed as options[:with].

There is also a list of options that could be used along with validators:

  • :on - Specifies when this validation is active. Runs in all validation contexts by default (nil), other options are :create and :update.

  • :if - Specifies a method, proc or string to call to determine if the validation should occur (e.g. if: :allow_validation, or if: Proc.new { |user| user.signup_step > 2 }). The method, proc or string should return or evaluate to atrue or false value.

  • :unless - Specifies a method, proc or string to call to determine if the validation should not occur (e.g. unless: :skip_validation, or unless: Proc.new { |user| user.signup_step <= 2 }). The method, proc or string should return or evaluate to a true or false value.

  • :strict - if the :strict option is set to true will raise ActiveModel::StrictValidationFailed instead of adding the error. :strict option can also be set to any other exception.

Example:

validates :password, presence: true, confirmation: true, if: :password_required?
validates :token, uniqueness: true, strict: TokenGenerationException

Finally, the options :if:unless:on:allow_blank:allow_nil:strict and :message can be given to one specific validator, as a hash:

validates :password, presence: { if: :password_required?, message: 'is forgotten.' }, confirmation: true

Source: show | on GitHub

validates!(*attributes)Link

This method is used to define validations that cannot be corrected by end users and are considered exceptional. So each validator defined with bang or :strict option set to true will always raiseActiveModel::StrictValidationFailed instead of adding error when validation fails. See validates for more information about the validation itself.

class Person
include ActiveModel::Validations attr_accessor :name
validates! :name, presence: true
end person = Person.new
person.name = ''
person.valid?
# => ActiveModel::StrictValidationFailed: Name can't be blank

Source: show | on GitHub

validates_each(*attr_names, &block)Link

Validates each attribute against a block.

class Person
include ActiveModel::Validations attr_accessor :first_name, :last_name validates_each :first_name, :last_name, allow_blank: true do |record, attr, value|
record.errors.add attr, 'starts with z.' if value.to_s[0] == z
end
end

Options:

  • :on - Specifies the context where this validation is active (e.g. on: :create or on: :custom_validation_context)

  • :allow_nil - Skip validation if attribute is nil.

  • :allow_blank - Skip validation if attribute is blank.

  • :if - Specifies a method, proc or string to call to determine if the validation should occur (e.g. if: :allow_validation, or if: Proc.new { |user| user.signup_step > 2 }). The method, proc or string should return or evaluate to atrue or false value.

  • :unless - Specifies a method, proc or string to call to determine if the validation should not occur (e.g. unless: :skip_validation, or unless: Proc.new { |user| user.signup_step <= 2 }). The method, proc or string should return or evaluate to a true or false value.

Source: show | on GitHub

validates_with(*args, &block)Link

Passes the record off to the class or classes specified and allows them to add errors based on more complex conditions.

class Person
include ActiveModel::Validations
validates_with MyValidator
end class MyValidator < ActiveModel::Validator
def validate(record)
if some_complex_logic
record.errors.add :base, 'This record is invalid'
end
end private
def some_complex_logic
# ...
end
end

You may also pass it multiple classes, like so:

class Person
include ActiveModel::Validations
validates_with MyValidator, MyOtherValidator, on: :create
end

Configuration options:

  • :on - Specifies when this validation is active (:create or :update.

  • :if - Specifies a method, proc or string to call to determine if the validation should occur (e.g. if: :allow_validation, or if: Proc.new { |user| user.signup_step > 2 }). The method, proc or string should return or evaluate to atrue or false value.

  • :unless - Specifies a method, proc or string to call to determine if the validation should not occur (e.g. unless: :skip_validation, or unless: Proc.new { |user| user.signup_step <= 2 }). The method, proc or string should return or evaluate to a true or false value.

  • :strict - Specifies whether validation should be strict. See ActiveModel::Validation#validates! for more information.

If you pass any additional configuration options, they will be passed to the class and available as options:

class Person
include ActiveModel::Validations
validates_with MyValidator, my_custom_key: 'my custom value'
end class MyValidator < ActiveModel::Validator
def validate(record)
options[:my_custom_key] # => "my custom value"
end
end

Source: show | on GitHub

validators()Link

List all validators that are being used to validate the model using validates_with method.

class Person
include ActiveModel::Validations validates_with MyValidator
validates_with OtherValidator, on: :create
validates_with StrictValidator, strict: true
end Person.validators
# => [
# #<MyValidator:0x007fbff403e808 @options={}>,
# #<OtherValidator:0x007fbff403d930 @options={on: :create}>,
# #<StrictValidator:0x007fbff3204a30 @options={strict:true}>
# ]

Source: show | on GitHub

validators_on(*attributes)Link

List all validators that are being used to validate a specific attribute.

class Person
include ActiveModel::Validations attr_accessor :name , :age validates_presence_of :name
validates_inclusion_of :age, in: 0..99
end Person.validators_on(:name)
# => [
# #<ActiveModel::Validations::PresenceValidator:0x007fe604914e60 @attributes=[:name], @options={}>,
# #<ActiveModel::Validations::InclusionValidator:0x007fe603bb8780 @attributes=[:age], @options={in:0..99}>
# ]

rails提供的validators的更多相关文章

  1. Rails :布局和视图渲染

    原文地址: http://guides.ruby-china.org/layouts_and_rendering.html Rails 布局和视图渲染 本文介绍 Action Controller 和 ...

  2. Windows下: RubyMine + Ruby On Rails + mysql 搭建开发环境

    最近在接手一个手机项目.在搭建环境的过程中,遇到了一些问题,在下文中已做记录,并奉上个人的解决方案. 开发环境 win2003 ;  JetBrains RubyMine6.3.3 1.  下载最新版 ...

  3. [Ruby on Rails系列]3、初试Rails:使用Rails开发第一个Web程序

    本系列前两部分已经介绍了如何配置Ruby on Rails开发环境,现在终于进入正题啦! Part1.开发前的准备 本次的主要任务是开发第一个Rails程序.需要特别指出的是,本次我选用了一个(Paa ...

  4. Rails 撤销操作

    即使再小心,在开发 Rails 应用程序过程中仍然可能犯错.幸运的是,Rails 提供了一些工具能够帮助你进行复原. 举例来说,一个常见的情况是,你想更改控制器的名字,这时你就要撤销生成的代码.生成控 ...

  5. The Six Types of Rails Association

    翻译整理自:http://guides.rubyonrails.org/v3.2.13/association_basics.html 想吐槽一句,http://guides.ruby-china.o ...

  6. Ruby on Rails Tutorial读书笔记-1

    只是怕忘了命令,全部撸一次,记个大概.. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 安装Ruby之前,先要安装RVM: curl -L https://get.rvm.io | bas ...

  7. 11月24日 layouts and rendering in rails(部分没有看)

    http://guides.rubyonrails.org/layouts_and_rendering.html  中文 This guide covers the basic layout feat ...

  8. rails中accepts_nested_attributes_for应用

    Model: class Blog < ActiveRecord::Base has_many :strip_rules accepts_nested_attributes_for :strip ...

  9. 杂项-frame:Rails框架

    ylbtech-杂项-frame:Rails框架 Rails框架首次提出是在2004年7月,它的研发者是26岁的丹麦人David Heinemeier Hansson.不同于已有复杂的Web 开发框架 ...

随机推荐

  1. 本号讯 | 永不消失的协作“空间站”开课;微软推出微软云Azure文档网站

    8月29日,针对企业常面临的“协同办公”困难,开展以“还有这种操作?永不消失的协作'空间站'”为主题的协同办公培训课. 课程内容包含:在Office 365环境中,如何利用Teams与Groups等功 ...

  2. Securityonion介绍

        下载地址     https://github.com/Security-Onion-Solutions/security-onion/blob/master/Verify_ISO.md   ...

  3. 洛谷 P1433 吃奶酪

    题目描述 房间里放着n块奶酪.一只小老鼠要把它们都吃掉,问至少要跑多少距离?老鼠一开始在(0,0)点处. 输入输出格式 输入格式: 第一行一个数n (n<=15) 接下来每行2个实数,表示第i块 ...

  4. 面向对象OONo.3单元总结

    一,JML语言 1)JML理论基础:JML是一类语言,用来描述一个方法或一个类的功能.以及这个类在实现这个功能时需要的条件.可能改变的全局变量.以及由于条件问题不能实现功能时这个方法或类的行为,具有明 ...

  5. 禅与 Objective-C 编程艺术(Zen and the Art of the Objective-C Craftsmanship)

    英文版Zen and the Art of the Objective-C Craftsmanshiphttps://github.com/objc-zen/objc-zen-book 中文版禅与 O ...

  6. EXC_BAD_ACCESS调试

    有时候,你会遇到由EXCBADACCESS造成崩溃. 这篇文件会告诉你什么是EXCBADACCESS,以及它产生的原因.我还会提供一些EXCBADACCESS错误的解决方案. 1. 什么是 EXCBA ...

  7. jquery源码学习第一天

    第一天认识了jquery的大体结构,总的大范围是 (function() { // 这里是封装的代码,包括了各种方法.工具 window.JQuery = JQuery window.$ = $; } ...

  8. NOIP模拟赛 高级打字机

    [题目描述] 早苗入手了最新的高级打字机.最新款自然有着与以往不同的功能,那就是它具备撤销功能,厉害吧. 请为这种高级打字机设计一个程序,支持如下3种操作: 1.T x:在文章末尾打下一个小写字母x. ...

  9. 【期望dp】bzoj4832: [Lydsy1704月赛]抵制克苏恩

    这个题面怎么这么歧义…… Description 小Q同学现在沉迷炉石传说不能自拔.他发现一张名为克苏恩的牌很不公平.如果你不玩炉石传说,不必担心,小Q 同学会告诉你所有相关的细节.炉石传说是这样的一 ...

  10. MySQL的GTID复制与传统复制的相互切换

    MySQL的GTID复制与传统复制的相互转换 1. GTID复制转换成传统复制 1.1 环境准备 1.2 停止slave 1.3 查看当前主从状态 1.4 change master 1.5 启动主从 ...