转载自: http://www.cnblogs.com/lhyun/p/3448740.html
Instance Public methods
attribute_method?(attribute)Link

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

class Personinclude ActiveModel::Validationsattr_accessor :name
endUser.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 Personinclude ActiveModel::Validationsvalidates_with MyValidatorvalidates_with OtherValidator, on: :createvalidates_with StrictValidator, strict: truevalidate :cannot_be_robotdef cannot_be_roboterrors.add(:base, 'A person cannot be a robot') if person_is_robotend
endPerson.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 Commentinclude ActiveModel::Validationsvalidate :must_be_friendsdef must_be_friendserrors.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 Commentinclude ActiveModel::Validationsvalidate do |comment|comment.must_be_friendsenddef must_be_friendserrors.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 Commentinclude ActiveModel::Validationsvalidate doerrors.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::EachValidatordef validate_each(record, attribute, value)record.errors.add attribute, (options[:message] || "is not an email") unlessvalue =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/end
endclass Personinclude ActiveModel::Validationsattr_accessor :name, :emailvalidates :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 Filminclude ActiveModel::Validationsclass TitleValidator < ActiveModel::EachValidatordef validate_each(record, attribute, value)record.errors.add attribute, "must start with 'the'" unless value =~ /\Athe/endendvalidates :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 Personinclude ActiveModel::Validationsattr_accessor :namevalidates! :name, presence: true
endperson = 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 Personinclude ActiveModel::Validationsattr_accessor :first_name, :last_namevalidates_each :first_name, :last_name, allow_blank: true do |record, attr, value|record.errors.add attr, 'starts with z.' if value.to_s[0] == zend
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 Personinclude ActiveModel::Validationsvalidates_with MyValidator
endclass MyValidator < ActiveModel::Validatordef validate(record)if some_complex_logicrecord.errors.add :base, 'This record is invalid'endendprivatedef some_complex_logic# ...end
end

You may also pass it multiple classes, like so:

class Personinclude ActiveModel::Validationsvalidates_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 Personinclude ActiveModel::Validationsvalidates_with MyValidator, my_custom_key: 'my custom value'
endclass MyValidator < ActiveModel::Validatordef 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 Personinclude ActiveModel::Validationsvalidates_with MyValidatorvalidates_with OtherValidator, on: :createvalidates_with StrictValidator, strict: true
endPerson.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 Personinclude ActiveModel::Validationsattr_accessor :name , :agevalidates_presence_of :namevalidates_inclusion_of :age, in: 0..99
endPerson.validators_on(:name)
# => [
#       #<ActiveModel::Validations::PresenceValidator:0x007fe604914e60 @attributes=[:name], @options={}>,
#       #<ActiveModel::Validations::InclusionValidator:0x007fe603bb8780 @attributes=[:age], @options={in:0..99}>
#    ]

Instance Public methods
attribute_method?(attribute)Link

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

class Personinclude ActiveModel::Validationsattr_accessor :name
endUser.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 Personinclude ActiveModel::Validationsvalidates_with MyValidatorvalidates_with OtherValidator, on: :createvalidates_with StrictValidator, strict: truevalidate :cannot_be_robotdef cannot_be_roboterrors.add(:base, 'A person cannot be a robot') if person_is_robotend
endPerson.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 Commentinclude ActiveModel::Validationsvalidate :must_be_friendsdef must_be_friendserrors.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 Commentinclude ActiveModel::Validationsvalidate do |comment|comment.must_be_friendsenddef must_be_friendserrors.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 Commentinclude ActiveModel::Validationsvalidate doerrors.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::EachValidatordef validate_each(record, attribute, value)record.errors.add attribute, (options[:message] || "is not an email") unlessvalue =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/end
endclass Personinclude ActiveModel::Validationsattr_accessor :name, :emailvalidates :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 Filminclude ActiveModel::Validationsclass TitleValidator < ActiveModel::EachValidatordef validate_each(record, attribute, value)record.errors.add attribute, "must start with 'the'" unless value =~ /\Athe/endendvalidates :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 Personinclude ActiveModel::Validationsattr_accessor :namevalidates! :name, presence: true
endperson = 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 Personinclude ActiveModel::Validationsattr_accessor :first_name, :last_namevalidates_each :first_name, :last_name, allow_blank: true do |record, attr, value|record.errors.add attr, 'starts with z.' if value.to_s[0] == zend
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 Personinclude ActiveModel::Validationsvalidates_with MyValidator
endclass MyValidator < ActiveModel::Validatordef validate(record)if some_complex_logicrecord.errors.add :base, 'This record is invalid'endendprivatedef some_complex_logic# ...end
end

You may also pass it multiple classes, like so:

class Personinclude ActiveModel::Validationsvalidates_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 Personinclude ActiveModel::Validationsvalidates_with MyValidator, my_custom_key: 'my custom value'
endclass MyValidator < ActiveModel::Validatordef 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 Personinclude ActiveModel::Validationsvalidates_with MyValidatorvalidates_with OtherValidator, on: :createvalidates_with StrictValidator, strict: true
endPerson.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 Personinclude ActiveModel::Validationsattr_accessor :name , :agevalidates_presence_of :namevalidates_inclusion_of :age, in: 0..99
endPerson.validators_on(:name)
# => [
#       #<ActiveModel::Validations::PresenceValidator:0x007fe604914e60 @attributes=[:name], @options={}>,
#       #<ActiveModel::Validations::InclusionValidator:0x007fe603bb8780 @attributes=[:age], @options={in:0..99}>
#    ]

转载于:https://www.cnblogs.com/tabCtrlShift/p/6294508.html

rails提供的validators相关推荐

  1. [rails] 我的订餐系统 -- 小试ruby on rails(转)

    前言         近期在java社区中一种新的脚本语言ruby,及用ruby开发的一个wab框架 rails也热闹了起来.引起了不少的java开发人员的关注. 本人平时还是很少接触脚本语言方面东东 ...

  2. ruby语言开源Web应用框架 Ruby on Rails 简介

    目录 Ruby on Rails是什么 历史 Rails 的 MVC 架构 Web 服务器支持 数据库支持 系统要求 集成开发环境 Ruby on Rails是什么 Ruby on Rails(官方简 ...

  3. Ruby on rails

    转自https://www.cnblogs.com/fantiantian/p/3401913.html Ruby on rails初体验(一) 接触ruby on rails 已经有一段时间了,想记 ...

  4. Rails Migrations

    Rails鼓励敏捷,迭代的开发风格.我们不会第一次就期望得到正确的东西.相反我们会写测试,并与客户沟通以加强我们对事物的理解. 要做到这些,我们就需要大量的实践工作.我们写测试来帮助规划我们接口,以便 ...

  5. 第四章 Rails 背后的 Ruby

    第四章 Rails 背后的 Ruby 有了第三章中的例子做铺垫,本章将为你介绍一些对 Rails 来说很重要的 Ruby 知识.Ruby 语言的知识点很多,不过对一个 Rails 开发者而言需要掌握的 ...

  6. Rails安全导读【完】

    本文的译言链接是: [url]http://www.yeeyan.com/articles/view/blackanger/18007[/url] 8.注入 - 注入这类***是给一个web应用引入恶 ...

  7. Rails Security (上)

    Lobsiinvok · 2016/03/09 10:20 Author: Lobsiinvok 0x00 前言 Rails是Ruby广泛应用方式之一,在Rails平台上设计出一套独特的MVC开发架构 ...

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

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

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

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

最新文章

  1. 32位postman_谷歌浏览器下载安装postman教程(详细)
  2. 就业丨速成班出来的AI人才,老板到底要不要?
  3. Redux vs Mobx系列(-):immutable vs mutable
  4. anaconda 怎么安装xlrd_Anaconda 安装 tensorflow 和 keras
  5. 无需用户输入,Adobe提出自动高质量图像合成新方法
  6. 8.Azure文件(文件共享)-NAS(中)
  7. 中国基座臂行业市场供需与战略研究报告
  8. 使用 JS 实现一个简单的日历
  9. 条码扫描二维码扫描—ZXing android 改进版本
  10. HDU 4280 Island Transport(HLPP板子)题解
  11. 输入法快捷键导致功能软件功能失效
  12. 西湖大学博导:都说不唯论文,那我们发表论文是为了什么?
  13. 抓包分析TCP首部,三次牵手四次分手过程,序列号确认号计算,为什么握手是三次挥手是四次?
  14. 我叫mt4公会攻城战服务器维护中,公会攻城战也要讲战术《我叫MT4》攻城战策略解析...
  15. utc时间 单位换算_将UTC日期转换为毫秒
  16. Java面试题大全带答案110道(持续更新)
  17. java swing小程序:手动绘制美国队长盾牌
  18. docker搭建LNRP环境
  19. 中国科技技术大学潘建伟计算机,中国研制量子计算机“九章” 比超级计算机快一百万亿倍...
  20. linux下最好的chm阅读器KchmViewer,安装使用/与oklular,xCHM,gnochm简单比较

热门文章

  1. MySQL影响性能的因素
  2. hdu1251(trie树)
  3. BAPI:KBPP_EXTERN_UPDATE_CO, TCODE:CJ30/CJ40 第二部分
  4. 零基础带你学习MySQL—Delete语句以及注意事项(九)
  5. c++字符数组整数转换中文大写金额的形式_如何对PHP日期数组进行排序
  6. 特殊用法(AHB写)
  7. 每天固定往一个银行卡存入100元,5年之后会有多大变化?有人能坚持吗?
  8. 大家有什么n刷的小说,可以推荐一下吗?
  9. 你有过什么令你难忘的约会经历?
  10. 坐异性朋友的车时,能坐在副驾驶吗?