RoR读书笔记 --- Active Record Validations and Callbacks

来源:互联网 发布:导航网站源码 编辑:程序博客网 时间:2024/05/17 23:44

Validates:

1)  :acceptance  --- Validates that a checkbox on the user interface was checked when a form was submitted

可以用于诸如对用户在页面上同意所列合同条款等(checkbox)的确认,可以是虚拟字段

这里需要借助一下前面创建的model --- person http://blog.csdn.net/kunshan_shenbin/article/details/7259246

在model里添加:validates :terms, :acceptance => true

在页面上添加checkbox:

<div class="field">    <%= f.label :terms %>    <%= f.check_box :terms %></div>
当页面提交时会触发验证,报告:Terms must be accepted


2) :validates_associated  --- when your model has associations with other models and they also need to be validated

3) :confirmation --- when you have two text fields that should receive exactly the same content

注意:程序会自动创建一个虚拟字段(name = 所需确认的字段名称后接 ' _confirmation ' )

View:

<%= text_field :person, :email %><%= text_field :person, :email_confirmation %>
Model:

validates :email, :confirmation => truevalidates :email_confirmation, :presence => true

4) :inclusion 和 :exclusion (包括和排除)

:inclusion --- the attributes’ values are not included in a given set

:exclusion --- the attributes’ values are included in a given set

示例:

validates :name, :exclusion => { :in => %w(a, b, c)}    #表示name不能是a,b或者c
5) :format --- the attributes’ values by testing whether they match a given regular expression, which is specified using the :with option

正则表达式验证:

validates :legacy_code, :format => { :with => /\A[a-zA-Z]+\z/, :message => "Only letters allowed" }
6) :length --- 长度限制

7) :numericality --- 数字

8) :presence --- 不能为空

9) :uniqueness --- 表示该字段在数据库中不能重复出现

10) :validates_with 和 :validates_each

:validates_with --- 需要自定义验证类来验证

class Person < ActiveRecord::Base  validates_with GoodnessValidator, :fields => [:first_name, :last_name]end class GoodnessValidator < ActiveModel::Validator  def validate(record)    if options[:fields].any?{|field| record.send(field) == "Evil" }      record.errors[:base] << "This person is evil"    end  endend
:validates_each --- 使用ruby block验证

class Person < ActiveRecord::Base  validates_each :name, :surname do |record, attr, value|    record.errors.add(attr, 'must start with upper case') if value =~ /\A[a-z]/  endend

callback

Creating an Object
before_validation
after_validation
before_save
around_save
before_create
around_create
after_create
after_save


Updating an Object

before_validation
after_validation
before_save
around_save
before_update
around_update
after_update
after_save


Destroying an Object

before_destroy
around_destroy
after_destroy

Observers

通过Observers,我们不需要修改model来实现callback.

譬如我们有这样的需求:每当创建一个新用户的时候发送一封邮件。

rails generate observer User

class UserObserver < ActiveRecord::Observer  def after_create(model)    # code to send confirmation email...  endend
在config/application.rb中注册这个Observers.

# Activate observers that should always be running.config.active_record.observers = :user_observer
如果不想在所有环境中都让他工作,我们可以把上面的代码加到对应的环境配置文件中,譬如development.rb。

如果需要共享Observers,我们可以这么做:

class MailerObserver < ActiveRecord::Observer  observe :registration, :user   def after_create(model)    # code to send confirmation email...  endend
当然,我们不能忘记注册他:

# Activate observers that should always be running.config.active_record.observers = :mailer_observer

参考资料:http://guides.rubyonrails.org/active_record_validations_callbacks.html


原创粉丝点击