您的位置:首页 > 编程语言 > Ruby

guides.rubyonrails.org 读书笔记(五)

2011-03-06 18:56 323 查看

Active Record Validations and Callbacks

1 The Object Life Cycle

Active Record provides hooks into this object life cycle
so that you can control your application and its data. 保证Rails object在创建、更新、销毁过程都是可控的。

(1)Validations allow you to ensure that only valid data is stored in your
database.

(2)Callbacks and observers allow you to trigger logic before or
after an alteration of an object’s state.

2 Validations Overview

2.1 Why Use Validations?

Validations are used to ensure that only valid data is saved into
your database. For example, it may be important to your application to
ensure that every user provides a valid email address and mailing
address.

There are several ways to validate data before it is saved into your
database, including

(1)native database constraints,

不利于测试和维护,但是在有另外的程序,比如来自移动API,同时使用这个数据库时,数据库层面的校验就非常重要了。

(2)client-side
validations,

快速反应,但客户端不易于控制,比如客户可能关闭来javascript

(3)controller-level validations,

这个层面的控制其实也是可以的,并不会如guide所说的那样不利于测试和维护。但是为了

(1)控制器本身的逻辑代码就不少,把校验移动出去,可以减少控制器的逻辑代码,防止fat

(2)遵从习惯,易于代码的传承管理,交接维护。

(4) model-level validations.

2.2 When Does Validation Happen?

There are two kinds of Active Record objects: those that correspond to a row inside your database and those that do not.

Validations are typically run before these commands are sent to the
database. If any validations fail, the object will be marked as invalid
and Active Record will not perform the INSERT
or UPDATE
operation.

Creating and saving a new record will send an SQL
INSERT
operation to the database. Updating an existing record will send an SQL
UPDATE
operation instead. Validations are typically run before these commands are sent to the database.

(1) 部分方法会触发校验;

(2)部分方法不会;

(3)save(:validate => false)

Note that save
also has the ability to skip validations if passed :validate => false
as argument. This technique should be used with caution.

2.4 valid?
and invalid?

You can also use this method on your own. valid?
triggers your validations and returns true if no errors were added to the object, and false otherwise.这里的原理其实很简单,校验失败后,对应的错误信息会被收集起来。而Active:Record也就是通过最终的错误信息来判断一个对象是否有效。也就是下面这句话的含义。

When Active Record is performing validations, any errors found can be accessed through the errors
instance method. By definition an object is valid if this collection is empty after running validations.

而此校验有两种方式:

(1)直接运行valid?

(2)会触发校验的方法:

Note that an object instantiated with new
will not report errors

even if it’s technically invalid, because validations are not run when using
new
.下面的程序就反映了这个问题,

2.5 errors[]

上面这段程序还值得关注的是errors。To verify whether or not a particular attribute of an object is valid, you can use errors[:attribute]
. It returns an array of all the errors for :attribute
. If there are no errors on the specified attribute, an empty array is returned.

ruby-1.9.2-p180 :013 > ps = Post.create(:name=>"", :title=>"jess")

=> #<Post id: nil, name: "", title: "jess", content: nil, created_at: nil, updated_at: nil>

ruby-1.9.2-p180 :014 > ps.valid?

=> false

ruby-1.9.2-p180 :015 > ps.errors

=> {:name=>["can't be blank"], :title=>["is too short (minimum is 5 characters)"]}

3 Validation Helpers

Active Record offers many pre-defined validation helpers that you can
use directly inside your class definitions. These helpers provide common
validation rules. Every time a validation fails, an error message is
added to the object’s errors
collection, and this message is associated with the field being validated.


Each helper accepts an arbitrary(任意的) number of attribute names, so with a
single line of code you can add the same kind of validation to several
attributes.

All of them accept the :on
and :message

options, which define when the validation should be run and what message should be added to the errors
collection if it fails, respectively. The :on
option takes one of the values :save
(the default), :create
or :update
. There is a default error message for each one of the validation helpers. These messages are used when the :message
option isn’t specified. Let’s take a look at each one of the available helpers.

(1)validates_format_of,

regular expression

(3)validates_length_of

The default error messages depend on the type of length validation being
performed. You can personalize these messages using the :wrong_length
, :too_long
, and :too_short
options and %{count}
as a placeholder for the number corresponding to the length constraint being used. You can still use the :message
option to specify an error message.

This helper counts characters by default, but you can split the value in a different way using the :tokenizer
option.

(4) validates_presence_of

If you want to be sure that an association is present, you’ll need to
test whether the foreign key used to map the association is present, and
not the associated object itself.

9 Callbacks Overview

Callbacks are methods that get called at certain moments of an object’s
life cycle. With callbacks it’s possible to write code that will run
whenever an Active Record object is created, saved, updated, deleted,
validated, or loaded from the database.

9.1 Callback Registration

In order to use the available callbacks, you need to register them. You
can do that by implementing them as ordinary methods, and then using a
macro-style class method to register them as callbacks.

It’s considered good practice to declare callback methods as being
protected or private. If left public, they can be called from outside of
the model and violate the principle of object encapsulation.

10 Available Callbacks

after_save
runs both on create and update, but always after
the more specific callbacks after_create
and after_update
, no matter the order in which the macro calls were executed.

The after_initialize
callback will be called whenever an Active Record object is instantiated, either by directly using new
or when a record is loaded from the database. It can be useful to avoid the need to directly override your Active Record initialize
method.

The after_find
callback will be called whenever Active Record loads a record from the database. after_find
is called before after_initialize
if both are defined.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: