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本身
而下面这些函数则是忽略validation判断的,直接写入数据库,也不管是不是合法
这里save用时参数加上这个就可以逃过validation判断
如何判断object是否valid呢,我们使用的方法是valid?和invalid?用法如下
假如create的非法,我们需要知道错误信息,那么我们就要使用errors返回所有的错误信息了,他是一个hash,key为错误的列的名字,data为错误信息。所以我们可以用errors[:name]得到关于name的错误信息。假如我们的create合法,那么errors为空
上面讲的很多东西都很是理论的,下面讲的东西将是真正的一些函数的使用。注意,helper在rails中有小工具的意思,你可以直接使用。
这些helper有一个共同的特点,他们都在你的model上添加上相应的validate,假如不通过那么就会在errors中加入错误信息。并且他们都可以接受:on和:message两个参数,on参数决定这个validation是施加在哪个操作上面的,默认的是:save还可以是:create或者:update;而:message参数则决定发生错误往errors里面写入的信息
他们的形式都是类似这样子的
validates调用函数,:terms_of_service是你列的名字,而acceptance:true是一个key=》data键值对形式,表明了helper使用的类型,下面一个个的说说
这个申请某个变量可接受的数据,它并不写入数据库,可以参考我们要求用户同意某种服务款项什么的,要求用户同意,但是我们不用把它写入数据库。
这个表明terms_of_service这个参数只接受true
而这个表明terms_of_service接受yes这个字符串,也就是说们key=>data(这个是个hash对,ruby中可以用key:data表示)data也可以是一个hash,里面的acceptkey表明了可以接受的参数形式
用来表示你的模型和其他模型有关联关系,你的模型包含着其他的模型,就例如下面的
但我们saveLibrary模型时,也会调用Book模型的save函数,同样的道理适用于valid?这个函数,注意不要再Book中也加入libraries的associate,因为这样会成循环,而且是死循环的。
这个是什么意思呢,他就是我们网页中需要输入两次相同信息的部分,比如初始化密码的设置,需要两次输入的一样什么的。它会自动和email_confirmation这个参数比较
我们在view层可以这样用
而在model定义的时候,我们要加上这个
就是简单的加上了email_confirmation必须出现
除了的意思,验证数据的值没有在参数里面的数据出现。
这个意思是subdomain函数不能出现www、us、ca或者jp%w是创建了一个字符串数据。exclusion指向一个hash,这个hash里面有一个key叫in它指向一个数组,这个数组中的数据都是非法参数。这里in,可以使用within是一样的,他们仅仅是别名的关系
和上面的整好相反,数据的值要出现在参数的数据中,用法相同,同样in可以换位within
定义可接受数据的格式
同样format指向一个hash,里面有一个withkey它指向一个正则表达式
这个是参数可接受的长度,这个并不一定是固定长度,他也是指向一个hash,可以进行各种设置
length指向的hash主要包含以上几种,可以同时使用,用逗号分开即可。
它的错误信息除了可以用:message指定外,还可以用:wrong_length、too_long、too_short指定,再这些信息中可以使用%{count}代替指定的长度,在too_long中它就显示最大的长度,too_short中就显示最小的长度。
它约定你的参数只能是数字,这里数字指整数和浮点数。假如你numericality指向一个hash,里面only_integer设置为true,那么他就仅接受整数了。
用法如下
除了only_integer,他还接受
大于
大于等于
等于
如果设置为true,那么它仅接受奇数
不能为空
为空
唯一的,他并不是给数据库列加上唯一约束,而是通过在存储前查找实现的。
uniqueness也可以指向一个hash,常用的是忽略大小写敏感用case_sensitive
一般的validation选项
允许空,它是通过nil函数确定的
允许blank,blank是rails中的函数,“”.blank?==true,"".nil?==flase这是blank?和nil?最大的区别,blank?关心的是内容,而nil更注重这个object是否存在。
strictvalidations
假如我们需要在validation不满足时不仅仅是一个异常,而是抛出一个错误,我们可以设置:strict为true,当然我们还可以用strict来设置自己的异常处理函数。当不满足validation时我们自行进行处理。
条件validation,就是使用if和unless判断断言满足或者不满足。
Youcanassociatethe
withasymbolcorrespondingtothenameofamethodthatwillgetcalledrightbeforevalidationhappens.Thisisthemostcommonlyusedoption.
这个主要说的是你可以用一个函数的符号放在if后面,然后你在声明这个函数,这个函数需要返回true或false
Youcanalsouseastringthatwillbeevaluatedusing
needstocontainvalidRubycode.Youshouldusethisoptiononlywhenthestringrepresentsareallyshortcondition.
你可以在if后面放一个string,这个string可以是一段可以在irb执行的ruby代码
Finally,it'spossibletoassociate
a
whichwillbecalled.Usinga
givesyoutheabilitytowriteaninlineconditioninsteadofaseparatemethod.Thisoptionisbestsuitedforone-liners.
可以在后面放置一个proc对象。
Sometimesitisusefultohavemultiplevalidationsuseonecondition,itcanbeeasilyachievedusing
还可以将所有的if或者unless约束打组写出,以前我们一个个为参数约定变量时,我们用validates,现在我们可以使用with_options对所有需要if或者unless的参数打组约定。这样,所有在with_options中的参数都会自动的加上if::is_admin?约束(就是指向符号的约束)。
Allvalidationsinsideof
willhaveautomaticallypassedthecondition
Ontheotherhand,whenmultipleconditionsdefinewhetherornotavalidationshouldhappen,an
beused.Moreover,youcanapplyboth
thesamevalidation.
假如你有多个if或者unless约束,你可以将他们放在一个数组中,然后用一个if或者unless约束就好啦
Thevalidationonlyrunswhenallthe
andnoneofthe
areevaluatedto
当默认的validationshelper无法满足你的需要时,你可以定义自己的validation。用法很简单,你需要继承ActiveModel::Validator类重写其中的
很简单吧,其实还有个更简单的办法,你可以像一般函数一样使用这些自定义的validations。就是你继承自
你看他的明明方式还是很有特点的,你的class叫XValidator那么你的约束就是叫x比如EmailValidator就是:email
最后,一些没讲的东西,我感觉用处不大的,我没有再翻译,仅粘贴英文
Youcanalsocreatemethodsthatverifythestateofyourmodelsandaddmessagestothe
method,passinginthesymbolsforthevalidationmethods'names.
Youcanpassmorethanonesymbolforeachclassmethodandtherespectivevalidationswillberuninthesameorderastheywereregistered.
Bydefaultsuchvalidationswillruneverytimeyoucall
Itisalsopossibletocontrolwhentorunthesecustomvalidationsbygivingan
tothe
witheither:
Inadditiontothe
coveredearlier,Railsprovidesanumberofmethodsforworkingwiththe
andinquiringaboutthevalidityofobjects.
Thefollowingisalistofthemostcommonlyusedmethods.Pleaserefertothe
foralistofalltheavailablemethods.
Returnsaninstanceoftheclass
allerrors.Eachkeyistheattributenameandthevalueisanarrayofstringswithallerrors.
usedwhenyouwanttochecktheerrormessagesforaspecificattribute.Itreturnsanarrayofstringswithallerrormessagesforthegivenattribute,eachstringwithoneerrormessage.Iftherearenoerrorsrelatedtotheattribute,itreturnsanempty
array.
The
letsyoumanuallyaddmessagesthatarerelatedtoparticularattributes.Youcanusethe
toviewthemessagesintheformtheymightbedisplayedtoauser.Thoseparticularmessagesgettheattributenameprepended(andcapitalized).
thenameoftheattributeyouwanttoaddthemessageto,andthemessageitself.
Anotherwaytodothisisusing
Youcanadderrormessagesthatarerelatedtotheobject'sstateasawhole,insteadofbeingrelatedtoaspecificattribute.Youcanusethismethodwhenyouwanttosaythattheobjectisinvalid,nomatterthevaluesofitsattributes.Since
anarray,youcansimplyaddastringtoitanditwillbeusedasanerrormessage.
The
isusedwhenyouintentionallywanttoclearallthemessagesinthe
Ofcourse,calling
aninvalidobjectwon'tactuallymakeitvalid:the
willnowbeempty,butthenexttimeyoucall
anymethodthattriestosavethisobjecttothedatabase,thevalidationswillrunagain.Ifanyofthevalidationsfail,the
willbefilledagain.
The
returnsthetotalnumberoferrormessagesfortheobject.
Onceyou'vecreatedamodelandaddedvalidations,ifthatmodeliscreatedviaawebform,youprobablywanttodisplayanerrormessagewhenoneofthevalidationsfail.
Becauseeveryapplicationhandlesthiskindofthingdifferently,Railsdoesnotincludeanyviewhelperstohelpyougeneratethesemessagesdirectly.However,duetotherichnumberofmethodsRailsgivesyoutointeractwithvalidationsingeneral,it's
fairlyeasytobuildyourown.Inaddition,whengeneratingascaffold,RailswillputsomeERBintothe
itgeneratesthatdisplaysthefulllistoferrorsonthatmodel.
Assumingwehaveamodelthat'sbeensavedinaninstancevariablenamed
itlookslikethis:
Furthermore,ifyouusetheRailsformhelperstogenerateyourforms,whenavalidationerroroccursonafield,itwillgenerateanextra
theentry.
Youcanthenstylethisdivhoweveryou'dlike.ThedefaultscaffoldthatRailsgenerates,forexample,addsthisCSSrule:
Thismeansthatanyfieldwithanerrorendsupwitha2pixelredborder.
就是像下面的似的东西
它是用来保证只有合法的数据才能够进入你的数据库,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?用法如下
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
validates_associated
用来表示你的模型和其他模型有关联关系,你的模型包含着其他的模型,就例如下面的但我们saveLibrary模型时,也会调用Book模型的save函数,同样的道理适用于valid?这个函数,注意不要再Book中也加入libraries的associate,因为这样会成循环,而且是死循环的。
confirmation
我们在view层可以这样用
而在model定义的时候,我们要加上这个
exclusion
除了的意思,验证数据的值没有在参数里面的数据出现。
inclusion
和上面的整好相反,数据的值要出现在参数的数据中,用法相同,同样in可以换位within
format
定义可接受数据的格式
length
这个是参数可接受的长度,这个并不一定是固定长度,他也是指向一个hash,可以进行各种设置length指向的hash主要包含以上几种,可以同时使用,用逗号分开即可。
它的错误信息除了可以用:message指定外,还可以用:wrong_length、too_long、too_short指定,再这些信息中可以使用%{count}代替指定的长度,在too_long中它就显示最大的长度,too_short中就显示最小的长度。
numericality
它约定你的参数只能是数字,这里数字指整数和浮点数。假如你numericality指向一个hash,里面only_integer设置为true,那么他就仅接受整数了。用法如下
:greater_than-
大于
:greater_than_or_equal_to-
大于等于
:equal_to-
等于
:less_than-小于
:less_than_or_equal_to-小于等于
:odd-
如果设置为true,那么它仅接受奇数
:even-如果设置为true,那么它仅接受偶数
presence
不能为空
absence
为空
uniqueness
唯一的,他并不是给数据库列加上唯一约束,而是通过在存储前查找实现的。
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:ifand
:unlessoptions
withasymbolcorrespondingtothenameofamethodthatwillgetcalledrightbeforevalidationhappens.Thisisthemostcommonlyusedoption.
这个主要说的是你可以用一个函数的符号放在if后面,然后你在声明这个函数,这个函数需要返回true或false
5.2UsingaStringwith:if
and:unless
Youcanalsouseastringthatwillbeevaluatedusingevaland
needstocontainvalidRubycode.Youshouldusethisoptiononlywhenthestringrepresentsareallyshortcondition.
你可以在if后面放一个string,这个string可以是一段可以在irb执行的ruby代码
5.3UsingaProcwith:if
and:unless
Finally,it'spossibletoassociate:ifand
:unlesswith
a
Procobject
whichwillbecalled.Usinga
Procobject
givesyoutheabilitytowriteaninlineconditioninsteadofaseparatemethod.Thisoptionisbestsuitedforone-liners.
可以在后面放置一个
5.4GroupingConditionalvalidations
Sometimesitisusefultohavemultiplevalidationsuseonecondition,itcanbeeasilyachievedusingwith_options.
还可以将所有的if或者unless约束打组写出,以前我们一个个为参数约定变量时,我们用validates,现在我们可以使用with_options对所有需要if或者unless的参数打组约定。这样,所有在with_options中的参数都会自动的加上if::is_admin?约束(就是指向符号的约束)。
with_optionsblock
willhaveautomaticallypassedthecondition
if: :is_admin?
5.5CombiningValidationConditions
Ontheotherhand,whenmultipleconditionsdefinewhetherornotavalidationshouldhappen,anArraycan
beused.Moreover,youcanapplyboth
:ifand
:unlessto
thesamevalidation.
假如你有多个if或者unless约束,你可以将他们放在一个数组中,然后用一个if或者unless约束就好啦
:ifconditions
andnoneofthe
:unlessconditions
areevaluatedto
true.
PerformingCustomValidations
当默认的validationshelper无法满足你的需要时,你可以定义自己的validation。用法很简单,你需要继承ActiveModel::Validator类重写其中的validate方法。你约束时用
validates_with就可以了,在后面写上你自己定义的class名字。validate函数返回的erros
ActiveModel::EachValidator然后重写里面的validate_each函数,以后就可以用了。下面有一个例子。
最后,一些没讲的东西,我感觉用处不大的,我没有再翻译,仅粘贴英文
6.2CustomMethods(这个是指直接用方法约束你的参数)
Youcanalsocreatemethodsthatverifythestateofyourmodelsandaddmessagestotheerror scollectionwhentheyareinvalid.Youmustthenregisterthesemethodsbyusingthe
validateclass
method,passinginthesymbolsforthevalidationmethods'names.
Youcanpassmorethanonesymbolforeachclassmethodandtherespectivevalidationswillberuninthesameorderastheywereregistered.
valid?.
Itisalsopossibletocontrolwhentorunthesecustomvalidationsbygivingan
:onoption
tothe
validatemethod,
witheither:
:createor
:update.
7WorkingwithValidationErrors(各种errors的操作)
Inadditiontothevalid?and
invalid?methods
coveredearlier,Railsprovidesanumberofmethodsforworkingwiththe
errorscollection
andinquiringaboutthevalidityofobjects.
Thefollowingisalistofthemostcommonlyusedmethods.Pleaserefertothe
ActiveModel::Errorsdocumentation
foralistofalltheavailablemethods.
7.1errors
ReturnsaninstanceoftheclassActiveModel::Errorscontaining
allerrors.Eachkeyistheattributenameandthevalueisanarrayofstringswithallerrors.
7.2errors[]
errors[]is
usedwhenyouwanttochecktheerrormessagesforaspecificattribute.Itreturnsanarrayofstringswithallerrormessagesforthegivenattribute,eachstringwithoneerrormessage.Iftherearenoerrorsrelatedtotheattribute,itreturnsanempty
array.
7.3errors.add
Theaddmethod
letsyoumanuallyaddmessagesthatarerelatedtoparticularattributes.Youcanusethe
errors.full_messagesor
errors.to_amethods
toviewthemessagesintheformtheymightbedisplayedtoauser.Thoseparticularmessagesgettheattributenameprepended(andcapitalized).
addreceives
thenameoftheattributeyouwanttoaddthemessageto,andthemessageitself.
[]=setter
7.4errors[:base]
Youcanadderrormessagesthatarerelatedtotheobject'sstateasawhole,insteadofbeingrelatedtoaspecificattribute.Youcanusethismethodwhenyouwanttosaythattheobjectisinvalid,nomatterthevaluesofitsattributes.Sinceerrors[:base]is
anarray,youcansimplyaddastringtoitanditwillbeusedasanerrormessage.
7.5errors.clear
Theclearmethod
isusedwhenyouintentionallywanttoclearallthemessagesinthe
errorscollection.
Ofcourse,calling
errors.clearupon
aninvalidobjectwon'tactuallymakeitvalid:the
errorscollection
willnowbeempty,butthenexttimeyoucall
valid?or
anymethodthattriestosavethisobjecttothedatabase,thevalidationswillrunagain.Ifanyofthevalidationsfail,the
errorscollection
willbefilledagain.
7.6errors.size
Thesizemethod
returnsthetotalnumberoferrormessagesfortheobject.
8DisplayingValidationErrorsinViews
Onceyou'vecreatedamodelandaddedvalidations,ifthatmodeliscreatedviaawebform,youprobablywanttodisplayanerrormessagewhenoneofthevalidationsfail.Becauseeveryapplicationhandlesthiskindofthingdifferently,Railsdoesnotincludeanyviewhelperstohelpyougeneratethesemessagesdirectly.However,duetotherichnumberofmethodsRailsgivesyoutointeractwithvalidationsingeneral,it's
fairlyeasytobuildyourown.Inaddition,whengeneratingascaffold,RailswillputsomeERBintothe
_form.html.erbthat
itgeneratesthatdisplaysthefulllistoferrorsonthatmodel.
Assumingwehaveamodelthat'sbeensavedinaninstancevariablenamed
@post,
itlookslikethis:
<div>around
theentry.
相关文章推荐
- The Ruby On Rials Gudie -- Active Record基本
- The Ruby On Rials Gudie - say hello to rails
- The Ruby On Rials Gudie -- Active Record Associations
- The Ruby On Rials Gudie -- Active Record Migrations
- The Ruby On Rials Gudie -- Active Record Callbacks
- The Ruby On Rials Gudie -- Active Record Query Interface
- The Ruby On Rials Gudie - 文件夹
- [Ruby on Rails Issue] When Setting Sqlite version on the Gemfile, Show error "An error occurred while installing sqlite3 ",
- Ruby sitting on the CouchDB
- Ruby On Rails--Active Record Callbacks(回调)
- Ruby on rails开发从头来(四十六)- ActiveRecord基础(SQL和Active Record)
- Ruby on rails开发从头来(四十六)- ActiveRecord基础(SQL和Active Record)
- Ruby:Update value on specific row but keep the headers
- Ruby on Rials搭建外网
- Ruby on Rails案例学习:ChangingThePresent.org
- “media change: please insert the disc labeled” when trying to install Ruby on Rails [duplicate]
- Ruby on rails开发从头来(四十六)- ActiveRecord基础(SQL和Active Record)
- Ruby On Rails--Active Record Validations(校验)
- To build the ruby runtime environment on Mac
- Ruby On Rails--Active Record Query Interface(数据库查询)