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

The Ruby On Rials Gudie -- Active Record Validations

2013-11-04 22:10 369 查看
ActiveRecord验证

就是像下面的似的东西

它是用来保证只有合法的数据才能够进入你的数据库,model层的validation(这里类似于migration我们多使用英文)是最好的防止用户非法数据进入数据库的方法。

当我们new一个东西的时候,他并没有写入到数据库中,只有我们执行save时才会写入的。我们可以利用new_record来判断是否写入了数据库。而我们的validate就是发生在创建object之后,写入数据库之前。假如validate不通过,那么就返回一个invalid,并且不写入数据库。

下面这些函数只有数据valid的时候才会写入数据库,感叹号和非感叹号的区别就是在于感叹号数据非法时抛异常,而非感叹号返回false或者object本身

create


create!


save


save!


update


update!


而下面这些函数则是忽略validation判断的,直接写入数据库,也不管是不是合法

decrement!


decrement_counter


increment!


increment_counter


toggle!


touch


update_all


update_attribute


update_column


update_columns


update_counters


save(validate:
false)


这里save用时参数加上这个就可以逃过validation判断

如何判断object是否valid呢,我们使用的方法是valid?和invalid?用法如下

假如create的非法,我们需要知道错误信息,那么我们就要使用errors返回所有的错误信息了,他是一个hash,key为错误的列的名字,data为错误信息。所以我们可以用errors[:name]得到关于name的错误信息。假如我们的create合法,那么errors为空


ValidationHelpers

上面讲的很多东西都很是理论的,下面讲的东西将是真正的一些函数的使用。注意,helper在rails中有小工具的意思,你可以直接使用。

这些helper有一个共同的特点,他们都在你的model上添加上相应的validate,假如不通过那么就会在errors中加入错误信息。并且他们都可以接受:on和:message两个参数,on参数决定这个validation是施加在哪个操作上面的,默认的是:save还可以是:create或者:update;而:message参数则决定发生错误往errors里面写入的信息

他们的形式都是类似这样子的

validates
:terms_of_service
,
acceptance:
true


validates调用函数,:terms_of_service是你列的名字,而acceptance:true是一个key=》data键值对形式,表明了helper使用的类型,下面一个个的说说


acceptance

这个申请某个变量可接受的数据,它并不写入数据库,可以参考我们要求用户同意某种服务款项什么的,要求用户同意,但是我们不用把它写入数据库。

validates
:terms_of_service
,
acceptance:
true


这个表明terms_of_service这个参数只接受true

而这个表明terms_of_service接受yes这个字符串,也就是说们key=>data(这个是个hash对,ruby中可以用key:data表示)data也可以是一个hash,里面的acceptkey表明了可以接受的参数形式


validates_associated

用来表示你的模型和其他模型有关联关系,你的模型包含着其他的模型,就例如下面的

但我们saveLibrary模型时,也会调用Book模型的save函数,同样的道理适用于valid?这个函数,注意不要再Book中也加入libraries的associate,因为这样会成循环,而且是死循环的。


confirmation

这个是什么意思呢,他就是我们网页中需要输入两次相同信息的部分,比如初始化密码的设置,需要两次输入的一样什么的。它会自动和email_confirmation这个参数比较

我们在view层可以这样用

而在model定义的时候,我们要加上这个

就是简单的加上了email_confirmation必须出现


exclusion

除了的意思,验证数据的值没有在参数里面的数据出现。

这个意思是subdomain函数不能出现www、us、ca或者jp%w是创建了一个字符串数据。exclusion指向一个hash,这个hash里面有一个key叫in它指向一个数组,这个数组中的数据都是非法参数。这里in,可以使用within是一样的,他们仅仅是别名的关系


inclusion

和上面的整好相反,数据的值要出现在参数的数据中,用法相同,同样in可以换位within


format

定义可接受数据的格式

同样format指向一个hash,里面有一个withkey它指向一个正则表达式


length

这个是参数可接受的长度,这个并不一定是固定长度,他也是指向一个hash,可以进行各种设置

length指向的hash主要包含以上几种,可以同时使用,用逗号分开即可。

它的错误信息除了可以用:message指定外,还可以用:wrong_length、too_long、too_short指定,再这些信息中可以使用%{count}代替指定的长度,在too_long中它就显示最大的长度,too_short中就显示最小的长度。


numericality

它约定你的参数只能是数字,这里数字指整数和浮点数。假如你numericality指向一个hash,里面only_integer设置为true,那么他就仅接受整数了。

用法如下

除了only_integer,他还接受

:greater_than
-
大于

:greater_than_or_equal_to
-
大于等于

:equal_to
-
等于

:less_than
-小于

:less_than_or_equal_to
-小于等于

:odd
-
如果设置为true,那么它仅接受奇数

:even
-如果设置为true,那么它仅接受偶数


presence

不能为空


absence

为空


uniqueness

唯一的,他并不是给数据库列加上唯一约束,而是通过在存储前查找实现的。

uniqueness也可以指向一个hash,常用的是忽略大小写敏感用case_sensitive


CommonValidationOptions

一般的validation选项


allow_nil

允许空,它是通过nil函数确定的


allow_blank

允许blank,blank是rails中的函数,“”.blank?==true,"".nil?==flase这是blank?和nil?最大的区别,blank?关心的是内容,而nil更注重这个object是否存在。

strictvalidations

假如我们需要在validation不满足时不仅仅是一个异常,而是抛出一个错误,我们可以设置:strict为true,当然我们还可以用strict来设置自己的异常处理函数。当不满足validation时我们自行进行处理。


ConditionalValidation

条件validation,就是使用if和unless判断断言满足或者不满足。


5.1UsingaSymbolwith
:if
and
:unless

Youcanassociatethe
:if
and
:unless
options
withasymbolcorrespondingtothenameofamethodthatwillgetcalledrightbeforevalidationhappens.Thisisthemostcommonlyusedoption.

这个主要说的是你可以用一个函数的符号放在if后面,然后你在声明这个函数,这个函数需要返回true或false


5.2UsingaStringwith
:if
and
:unless

Youcanalsouseastringthatwillbeevaluatedusing
eval
and
needstocontainvalidRubycode.Youshouldusethisoptiononlywhenthestringrepresentsareallyshortcondition.

你可以在if后面放一个string,这个string可以是一段可以在irb执行的ruby代码


5.3UsingaProcwith
:if
and
:unless

Finally,it'spossibletoassociate
:if
and
:unless
with
a
Proc
object
whichwillbecalled.Usinga
Proc
object
givesyoutheabilitytowriteaninlineconditioninsteadofaseparatemethod.Thisoptionisbestsuitedforone-liners.

可以在后面放置一个proc对象。


5.4GroupingConditionalvalidations

Sometimesitisusefultohavemultiplevalidationsuseonecondition,itcanbeeasilyachievedusing
with_options
.

还可以将所有的if或者unless约束打组写出,以前我们一个个为参数约定变量时,我们用validates,现在我们可以使用with_options对所有需要if或者unless的参数打组约定。这样,所有在with_options中的参数都会自动的加上if::is_admin?约束(就是指向符号的约束)。

Allvalidationsinsideof
with_options
block
willhaveautomaticallypassedthecondition
if:
:is_admin?


5.5CombiningValidationConditions

Ontheotherhand,whenmultipleconditionsdefinewhetherornotavalidationshouldhappen,an
Array
can
beused.Moreover,youcanapplyboth
:if
and
:unless
to
thesamevalidation.

假如你有多个if或者unless约束,你可以将他们放在一个数组中,然后用一个if或者unless约束就好啦

Thevalidationonlyrunswhenallthe
:if
conditions
andnoneofthe
:unless
conditions
areevaluatedto
true
.


PerformingCustomValidations

当默认的validationshelper无法满足你的需要时,你可以定义自己的validation。用法很简单,你需要继承ActiveModel::Validator类重写其中的
validate
方法。你约束时用
validates_with
就可以了,在后面写上你自己定义的class名字。validate函数返回的erros

很简单吧,其实还有个更简单的办法,你可以像一般函数一样使用这些自定义的validations。就是你继承自
ActiveModel::EachValidator
然后重写里面的validate_each函数,以后就可以用了。下面有一个例子。

你看他的明明方式还是很有特点的,你的class叫XValidator那么你的约束就是叫x比如EmailValidator就是:email

最后,一些没讲的东西,我感觉用处不大的,我没有再翻译,仅粘贴英文


6.2CustomMethods(这个是指直接用方法约束你的参数)

Youcanalsocreatemethodsthatverifythestateofyourmodelsandaddmessagestothe
error
s
collectionwhentheyareinvalid.Youmustthenregisterthesemethodsbyusingthe
validate
class
method,passinginthesymbolsforthevalidationmethods'names.

Youcanpassmorethanonesymbolforeachclassmethodandtherespectivevalidationswillberuninthesameorderastheywereregistered.

Bydefaultsuchvalidationswillruneverytimeyoucall
valid?
.
Itisalsopossibletocontrolwhentorunthesecustomvalidationsbygivingan
:on
option
tothe
validate
method,
witheither:
:create
or
:update
.


7WorkingwithValidationErrors(各种errors的操作)

Inadditiontothe
valid?
and
invalid?
methods
coveredearlier,Railsprovidesanumberofmethodsforworkingwiththe
errors
collection
andinquiringaboutthevalidityofobjects.

Thefollowingisalistofthemostcommonlyusedmethods.Pleaserefertothe
ActiveModel::Errors
documentation
foralistofalltheavailablemethods.


7.1
errors

Returnsaninstanceoftheclass
ActiveModel::Errors
containing
allerrors.Eachkeyistheattributenameandthevalueisanarrayofstringswithallerrors.


7.2
errors[]

errors[]
is
usedwhenyouwanttochecktheerrormessagesforaspecificattribute.Itreturnsanarrayofstringswithallerrormessagesforthegivenattribute,eachstringwithoneerrormessage.Iftherearenoerrorsrelatedtotheattribute,itreturnsanempty
array.


7.3
errors.add

The
add
method
letsyoumanuallyaddmessagesthatarerelatedtoparticularattributes.Youcanusethe
errors.full_messages
or
errors.to_a
methods
toviewthemessagesintheformtheymightbedisplayedtoauser.Thoseparticularmessagesgettheattributenameprepended(andcapitalized).
add
receives
thenameoftheattributeyouwanttoaddthemessageto,andthemessageitself.

Anotherwaytodothisisusing
[]=
setter


7.4
errors[:base]

Youcanadderrormessagesthatarerelatedtotheobject'sstateasawhole,insteadofbeingrelatedtoaspecificattribute.Youcanusethismethodwhenyouwanttosaythattheobjectisinvalid,nomatterthevaluesofitsattributes.Since
errors[:base]
is
anarray,youcansimplyaddastringtoitanditwillbeusedasanerrormessage.


7.5
errors.clear

The
clear
method
isusedwhenyouintentionallywanttoclearallthemessagesinthe
errors
collection.
Ofcourse,calling
errors.clear
upon
aninvalidobjectwon'tactuallymakeitvalid:the
errors
collection
willnowbeempty,butthenexttimeyoucall
valid?
or
anymethodthattriestosavethisobjecttothedatabase,thevalidationswillrunagain.Ifanyofthevalidationsfail,the
errors
collection
willbefilledagain.


7.6
errors.size

The
size
method
returnsthetotalnumberoferrormessagesfortheobject.


8DisplayingValidationErrorsinViews

Onceyou'vecreatedamodelandaddedvalidations,ifthatmodeliscreatedviaawebform,youprobablywanttodisplayanerrormessagewhenoneofthevalidationsfail.

Becauseeveryapplicationhandlesthiskindofthingdifferently,Railsdoesnotincludeanyviewhelperstohelpyougeneratethesemessagesdirectly.However,duetotherichnumberofmethodsRailsgivesyoutointeractwithvalidationsingeneral,it's
fairlyeasytobuildyourown.Inaddition,whengeneratingascaffold,RailswillputsomeERBintothe
_form.html.erb
that
itgeneratesthatdisplaysthefulllistoferrorsonthatmodel.

Assumingwehaveamodelthat'sbeensavedinaninstancevariablenamed
@post
,
itlookslikethis:

Furthermore,ifyouusetheRailsformhelperstogenerateyourforms,whenavalidationerroroccursonafield,itwillgenerateanextra
<div>
around
theentry.

Youcanthenstylethisdivhoweveryou'dlike.ThedefaultscaffoldthatRailsgenerates,forexample,addsthisCSSrule:

Thismeansthatanyfieldwithanerrorendsupwitha2pixelredborder.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ruby on rails guide