Anda di halaman 1dari 53

Moreatrubyonrails.

org: Overview|Download|Deploy|Code|Screencasts|Documentation|Ecosystem|Community|Blog

AGuidetoActiveRecordAssociations
ThisguidecoverstheassociationfeaturesofActiveRecord.Byreferringto thisguide,youwillbeableto:
DeclareassociationsbetweenActiveRecordmodels UnderstandthevarioustypesofActiveRecordassociations Usethemethodsaddedtoyourmodelsbycreatingassociations

Chapters
1. WhyAssociations? 2. TheTypesofAssociations Theb l n s t Association eog_o Theh s o e a _ n Association Theh s m n Association a_ay Theh s m n t r u h a _ a y : h o g Association Theh s o e : h o g Association a_ntruh Theh s a d b l n s t _ a y a _ n _ e o g _ o m n Association ChoosingBetweenb l n s t andh s o e eog_o a_n ChoosingBetweenh s m n t r u h a _ a y : h o g andh s a d b l n s t _ a y a_n_eog_omn PolymorphicAssociations SelfJoins 3. Tips,Tricks,andWarnings ControllingCaching AvoidingNameCollisions UpdatingtheSchema ControllingAssociationScope 4. DetailedAssociationReference b l n s t AssociationReference eog_o hsoe a _ n AssociationReference h s m n AssociationReference a_ay hsadblnst_ay a _ n _ e o g _ o m n AssociationReference AssociationCallbacks AssociationExtensions 5. Changelog

1WhyAssociations?
Whydoweneedassociationsbetweenmodels?Becausetheymakecommonoperationssimplerandeasierinyourcode.Forexample,considera simpleRailsapplicationthatincludesamodelforcustomersandamodelfororders.Eachcustomercanhavemanyorders.Withoutassociations,the modeldeclarationswouldlooklikethis:

cas ls

Csoecieeod:ae utmr<AtvRcr:Bs ed n cas ls Odr<AtvRcr:Bs recieeod:ae ed n

Now,supposewewantedtoaddaneworderforanexistingcustomer.We dneedtodosomethinglikethis:

@ d e =Odrcet( re.rae : d _ae e d = > Tm ie .o, nw : c e_d i = > @ c e .d i)

Orconsiderdeletingacustomer,andensuringthatallofitsordersgetdeletedaswell:

@ d e =Odrwee re.hr( : c e_d i = > @ c e .d i) @ d e . ec ah d o |re| odr odrdsry re.eto ed n @ c e .eto dsry

WithActiveRecordassociations,wecanstreamlinetheseandotheroperationsbydeclarativelytellingRailsthatthereisaconnectionbetween thetwomodels.Here stherevisedcodeforsettingupcustomersandorders:

cas ls Csoecieeod:ae utmr<AtvRcr:Bs hsmn a_ay : d e , :eed d e = > :e d ed n cas ls

cas ls Odr<AtvRcr:Bs recieeod:ae blnst eog_o : c e ed n

Withthischange,creatinganeworderforaparticularcustomeriseasier:

@ d e = @ c e .rescet( odr.rae : d _ae e d = > Tm ie .o) nw

Deletingacustomerandallofitsordersismucheasier:

@ c e .eto dsry

Tolearnmoreaboutthedifferenttypesofassociations,readthenextsectionofthisguide.That sfollowedbysometipsandtricksforworkingwith associations,andthenbyacompletereferencetothemethodsandoptionsforassociationsinRails.

2TheTypesofAssociations
InRails,anassociationisaconnectionbetweentwoActiveRecordmodels.Associationsareimplementedusingmacrostylecalls,sothatyoucan declarativelyaddfeaturestoyourmodels.Forexample,bydeclaringthatonemodelb l n s t another,youinstructRailstomaintainPrimaryKey eog_o ForeignKeyinformationbetweeninstancesofthetwomodels,andyoualsogetanumberofutilitymethodsaddedtoyourmodel.Railssupportssix typesofassociations:
blnst eog_o hsoe a_n hsmn a_ay hsmntruh a_ay:hog hsoe:hog a_ntruh hsadblnst_ay a_n_eog_omn

Intheremainderofthisguide,you lllearnhowtodeclareandusethevariousformsofassociations.Butfirst,aquickintroductiontothesituations whereeachassociationtypeisappropriate.

2.1Theb e

g _ Association

Ab l n s t associationsetsupaonetooneconnectionwithanothermodel,suchthateachinstanceofthedeclaringmodelbelongstoone eog_o instanceoftheothermodel.Forexample,ifyourapplicationincludescustomersandorders,andeachordercanbeassignedtoexactlyonecustomer, you ddeclaretheordermodelthisway:

cas ls Odr<AtvRcr:Bs recieeod:ae blnst eog_o : c e ed n

2.2Theh _ e a

2.2Theh _ e a Association
Ah s o e a _ n associationalsosetsup aonetooneconnectionwithanother model,butwithsomewhatdifferent semantics(andconsequences).This associationindicatesthateach instanceofamodelcontainsor possessesoneinstanceofanother model.Forexample,ifeachsupplier inyourapplicationhasonlyone account,you ddeclarethesupplier modellikethis:

cas ls Splecieeod:ae upir<AtvRcr:Bs hsoe a_n :c ac ed n

2.3Theh _ a a Association
Ah s m n associationindicatesa a_ay onetomanyconnectionwithanother model.You lloftenfindthisassociation ontheothersideofab l n s t eog_o association.Thisassociationindicates thateachinstanceofthemodelhaszero ormoreinstancesofanothermodel.For example,inanapplicationcontaining customersandorders,thecustomer modelcouldbedeclaredlikethis:

cas ls Csoecieeod:ae utmr<AtvRcr:Bs hsmn a_ay : d e ed n

Thenameoftheothermodelispluralizedwhendeclaringah s m n association. a_ay

2.4Theh _ a a : h g Association h
Ah s m n t r u h a _ a y : h o g association isoftenusedtosetupamanytomany connectionwithanothermodel.This associationindicatesthatthedeclaring modelcanbematchedwithzeroor moreinstancesofanothermodelby proceedingthroughathirdmodel.For example,consideramedicalpractice wherepatientsmakeappointmentsto seephysicians.Therelevant associationdeclarationscouldlooklike this:

cas ls Pyiin<AtvRcr:Bs hscacieeod:ae hsmn a_ay : a i e hsmn a_ay :ai e , :h g h = > : a i e ed n cas ls Apitet<AtvRcr:Bs ponmncieeod:ae blnst eog_o :h ii ca blnst eog_o :ai e ed n cas ls Ptet<AtvRcr:Bs aincieeod:ae hsmn a_ay : a i e hsmn a_ay :h ii ca , :h g h = > : a i e ed n

Thecollectionofjoinmodelscan bemanagedviatheAPI.For example,ifyouassign

pyiinptetains hsca.ains=ptet

newjoinmodelsarecreatedfornewlyassociatedobjects,andifsomearegonetheirrowsaredeleted.

Automaticdeletionofjoinmodelsisdirect,nodestroycallbacksaretriggered.

Theh s m n t r u h a _ a y : h o g associationisalsousefulforsettingupshortcutsthroughnestedh s m n associations.Forexample,ifadocument a_ay hasmanysections,andasectionhasmanyparagraphs,youmaysometimeswanttogetasimplecollectionofallparagraphsinthedocument.You couldsetthatupthisway:

cas ls Dcmncieeod:ae ouet<AtvRcr:Bs hsmn a_ay :e i c

hsmn a_ay :aa ah g , :h g h = > :e i c ed n cas ls Scin<AtvRcr:Bs etocieeod:ae blnst eog_o : c e d hsmn a_ay :aa ah g ed n cas ls Prgah<AtvRcr:Bs aarpcieeod:ae blnst eog_o :e i c ed n

With: h o g > : e t o s t r u h = s c i n specified,Railswillnowunderstand:

@ c e d .aarps prgah

2.5Theh _ e : h a

g Association h

Ah s o e : h o g associationsetsupaonetooneconnectionwithanothermodel.Thisassociationindicatesthatthedeclaringmodelcanbe a_ntruh matchedwithoneinstanceofanothermodelbyproceedingthroughathirdmodel.Forexample,ifeachsupplierhasoneaccount,andeachaccountis associatedwithoneaccounthistory,thenthecustomermodelcouldlooklikethis:

cas ls Splecieeod:ae upir<AtvRcr:Bs hsoe a_n :c ac hsoe a_n :c ac _i h , :h g h = > :c ac ed n cas ls Acut<AtvRcr:Bs concieeod:ae blnst eog_o : i e hsoe a_n :c ac _i h ed n cas ls

cas ls Acutitrcieeod:ae conHsoy<AtvRcr:Bs blnst eog_o :c ac ed n

2.6The h _ db a a _e Association

g_ _a

Ah s a d b l n s t _ a y a_n_eog_omn associationcreatesadirectmanyto manyconnectionwithanothermodel, withnointerveningmodel.For example,ifyourapplicationincludes assembliesandparts,witheach assemblyhavingmanypartsandeach partappearinginmanyassemblies, youcoulddeclarethemodelsthisway:

cas ls Asmlcieeod:ae seby<AtvRcr:Bs hsadblnst_ay a_n_eog_omn :a ed n cas ls Prcieeod:ae at<AtvRcr:Bs hsadblnst_ay a_n_eog_omn : ebi a e ed n

ed n

2.7ChoosingBetween b e g _ andh _ e a
Ifyouwanttosetupa11relationship betweentwomodels,you llneedtoadd b l n s t toone,andh s o e eog_o a _ n tothe other.Howdoyouknowwhichiswhich? Thedistinctionisinwhereyouplacethe foreignkey(itgoesonthetableforthe classdeclaringtheb l n s t eog_o association),butyoushouldgivesome thoughttotheactualmeaningofthedata aswell.Theh s o e a _ n relationshipsays thatoneofsomethingisyoursthatis, thatsomethingpointsbacktoyou.For example,itmakesmoresensetosaythat asupplierownsanaccountthanthatan accountownsasupplier.Thissuggests thatthecorrectrelationshipsarelikethis:

cas ls Splecieeod:ae upir<AtvRcr:Bs hsoe a_n :c ac ed n cas ls Acut<AtvRcr:Bs concieeod:ae blnst eog_o : i e ed n

Thecorrespondingmigrationmightlooklikethis:

cas ls CetSples<AtvRcr:Mgain raeupircieeod:irto df e cag hne cet_al raetbe

cet_al raetbe : i e d o || t tsrn .tig :ae ttmsap .ietms ed n cet_al raetbe :c ac d o || t titgr .nee : i _d e i tsrn .tig :c ac _ b e ttmsap .ietms ed n ed n ed n

Usingt i t g r : u p i r i makestheforeignkeynamingobviousandexplicit.IncurrentversionsofRails,youcanabstractawaythis .neesple_d implementationdetailbyusingt r f r n e s p l e instead. .eeecs:upir

2.8ChoosingBetweenh _ a h a :
whichallowsyoutomaketheassociationdirectly:

g andh _ d b h a a _e

g_ _a

Railsofferstwodifferentwaystodeclareamanytomanyrelationshipbetweenmodels.Thesimplerwayistouseh s a d b l n s t _ a y a_n_eog_omn,

cas ls Asmlcieeod:ae seby<AtvRcr:Bs hsadblnst_ay a_n_eog_omn :a ed n cas ls Prcieeod:ae at<AtvRcr:Bs hsadblnst_ay a_n_eog_omn : ebi a e ed n

Thesecondwaytodeclareamanytomanyrelationshipistouseh s m n t r u h a _ a y : h o g .Thismakestheassociationindirectly,throughajoinmodel:

cas ls Asmlcieeod:ae seby<AtvRcr:Bs hsmn a_ay :aie f

hsmn a_ay :a , :h g h = > :aie f ed n cas ls Mnfscieeod:ae aiet<AtvRcr:Bs blnst eog_o : eb a blnst eog_o :a ed n cas ls Prcieeod:ae at<AtvRcr:Bs hsmn a_ay :aie f hsmn a_ay : ebi a e , :h g h = > :aie f ed n

Thesimplestruleofthumbisthatyoushouldsetupah s m n t r u h a _ a y : h o g relationshipifyouneedtoworkwiththerelationshipmodelasan independententity.Ifyoudon tneedtodoanythingwiththerelationshipmodel,itmaybesimplertosetupah s a d b l n s t _ a y a_n_eog_omn relationship(thoughyou llneedtoremembertocreatethejoiningtableinthedatabase). Youshoulduseh s m n t r u h a _ a y : h o g ifyouneedvalidations,callbacks,orextraattributesonthejoinmodel.

2.9PolymorphicAssociations
Aslightlymoreadvancedtwistonassociationsisthepol morphicassociation.Withpolymorphicassociations,amodelcanbelongtomorethanone othermodel,onasingleassociation.Forexample,youmighthaveapicturemodelthatbelongstoeitheranemployeemodeloraproductmodel.Here s howthiscouldbedeclared:

cas ls Pcue<AtvRcr:Bs itrcieeod:ae blnst eog_o : aebe i ga , : hc i = > tu re ed n cas ls Epoecieeod:ae mlye<AtvRcr:Bs hsmn a_ay :i c e ,

: a

: a = > : aebe i ga ed n cas ls Pout<AtvRcr:Bs rdccieeod:ae hsmn a_ay :i c e , : a = > : aebe i ga ed n

Youcanthinkofapolymorphicb l n s t declarationassettingupaninterfacethatanyothermodelcanuse.FromaninstanceoftheE p o e eog_o mlye model,youcanretrieveacollectionofpictures:@ m l y e p c u e . epoe.itrs Similarly,youcanretrieve@ r d c . i t r s poutpcue. IfyouhaveaninstanceoftheP c u e i t r model,youcangettoitsparentvia@ i t r . m g a l .Tomakethiswork,youneedtodeclarebotha pcueiaebe foreignkeycolumnandatypecolumninthemodelthatdeclaresthepolymorphicinterface:

cas ls CetPcuecieeod:irto raeitrs<AtvRcr:Mgain df e cag hne cet_al raetbe :i c e d o || t tsrn .tig :ae titgr .nee : aebei i ga _d tsrn .tig : aebe i ga _ e ttmsap .ietms ed n ed n ed n

Thismigrationcanbesimplifiedbyusingthet r f r n e form: .eeecs

cas ls CetPcuecieeod:irto raeitrs<AtvRcr:Mgain df e cag hne

cet_al raetbe :i c e d o || t tsrn .tig :ae trfrne .eeecs : aebe i ga , : hc i = > tu re ttmsap .ietms ed n ed n ed n

2.10SelfJoins
Indesigningadatamodel,youwill sometimesfindamodelthatshould havearelationtoitself.Forexample, youmaywanttostoreallemployees inasingledatabasemodel,butbe abletotracerelationshipssuchas betweenmanagerandsubordinates. Thissituationcanbemodeledwith selfjoiningassociations:

cas ls Epoecieeod:ae mlye<AtvRcr:Bs hsmn a_ay : b d ae i , : a _ae c = > "ml e" Epo e blnst eog_o :aae g , : a _ae c = > "ml e" Epo e , : eg_e f i = > "aae_d mngri" ed n

Withthissetup,youcanretrieve@ m l y e s b r i a e and@ m l y e m n g r epoe.uodnts epoe.aae.

3Tips,Tricks,andWarnings
HereareafewthingsyoushouldknowtomakeefficientuseofActiveRecordassociationsinyourRailsapplications: Controllingcaching Avoidingnamecollisions Updatingtheschema Controllingassociationscope

3.1ControllingCaching
Alloftheassociationmethodsarebuiltaroundcaching,whichkeepstheresultofthemostrecentqueryavailableforfurtheroperations.Thecacheis evensharedacrossmethods.Forexample:

csoe.res utmrodr #rtivsodrrmtedtbs ereeresfohaaae csoe.ressz utmrodr.ie #uehahdcpfodr sstecceoyores csoe.resepy utmrodr.mt? #uehahdcpfodr sstecceoyores

Butwhatifyouwanttoreloadthecache,becausedatamighthavebeenchangedbysomeotherpartoftheapplication?Justpasst u tothe re associationcall:

csoe.res utmrodr #rtivsodrrmtedtbs ereeresfohaaae csoe.ressz utmrodr.ie #uehahdcpfodr sstecceoyores csoe.res utmrodr( tu re )epy .mt? #dsadhahdcpfodr icrstecceoyores #adgeakthaaae nosbcotedtbs

3.2AvoidingNameCollisions
Youarenotfreetousejustanynameforyourassociations.Becausecreatinganassociationaddsamethodwiththatnametothemodel,itisabad ideatogiveanassociationanamethatisalreadyusedforaninstancemethodofA t v R c r : B s .Theassociationmethodwouldoverridethe cieeod:ae basemethodandbreakthings.Forinstance,a t i u e orc n e t o arebadnamesforassociations. trbts oncin

3.3UpdatingtheSchema
Associationsareextremelyuseful,buttheyarenotmagic.Youareresponsibleformaintainingyourdatabaseschematomatchyourassociations.In practice,thismeanstwothings,dependingonwhatsortofassociationsyouarecreating.Forb l n s t associationsyouneedtocreateforeign eog_o keys,andforh s a d b l n s t _ a y a _ n _ e o g _ o m n associationsyouneedtocreatetheappropriatejointable. 3.3.1CreatingForeignKeysforb e g _ Associations

Whenyoudeclareab l n s t association,youneedtocreateforeignkeysasappropriate.Forexample,considerthismodel: eog_o

cas ls Odr<AtvRcr:Bs recieeod:ae blnst eog_o : c e ed n

Thisdeclarationneedstobebackedupbytheproperforeignkeydeclarationontheorderstable:

cas ls CetOdrcieeod:irto raeres<AtvRcr:Mgain df e cag hne cet_al raetbe : d e d o || t tdttm .aeie : d _ae e d tsrn .tig : d _ b e e titgr .nee : c e_d i ed n ed n ed n

Ifyoucreateanassociationsometimeafteryoubuildtheunderlyingmodel,youneedtoremembertocreateana d c l m migrationtoprovidethe d_oun necessaryforeignkey. 3.3.2CreatingJoinTablesforh _ d b a a _e g _ _ a Associations

Ifyoucreateah s a d b l n s t _ a y a _ n _ e o g _ o m n association,youneedtoexplicitlycreatethejoiningtable.Unlessthenameofthejointableisexplicitly specifiedbyusingthe: o n t b e j i _ a l option,ActiveRecordcreatesthenamebyusingthelexicalorderoftheclassnames.Soajoinbetween customerandordermodelswillgivethedefaultjointablenameofcustomers_ordersbecausecoutranksoinlexicalordering.

Theprecedencebetweenmodelnamesiscalculatedusingthe< operatorforS r n .Thismeansthatifthestringsareofdifferentlengths, tig andthestringsareequalwhencompareduptotheshortestlength,thenthelongerstringisconsideredofhigherlexicalprecedencethanthe shorterone.Forexample,onewouldexpectthetablespaper_boxesandpaperstogenerateajointablenameofpapers_paper_boxes becauseofthelengthofthenamepaper_boxes,butitinfactgeneratesajointablenameofpaper_boxes_papers(becausetheunderscore _ islexicographicallylessthan s incommonencodings).

Whateverthename,youmustmanuallygeneratethejointablewithanappropriatemigration.Forexample,considertheseassociations:

cas ls Asmlcieeod:ae seby<AtvRcr:Bs hsadblnst_ay a_n_eog_omn :a ed n cas ls Prcieeod:ae at<AtvRcr:Bs hsadblnst_ay a_n_eog_omn : ebi a e ed n

Theseneedtobebackedupbyamigrationtocreatethea s m l e _ a t table.Thistableshouldbecreatedwithoutaprimarykey: sebisprs

cas ls CetAsmlPrJiTbe<AtvRcr:Mgain raesebyatonalcieeod:irto df e cag hne cet_al raetbe : ebi _a a e , :d i = > fle as d o || t titgr .nee : eb _d a i titgr .nee :a _d i ed n ed n ed n

Wepass: d = a s toc e t _ a l becausethattabledoesnotrepresentamodel.That srequiredfortheassociationtoworkproperly.Ifyou i>fle raetbe observeanystrangebehaviorinah s a d b l n s t _ a y a _ n _ e o g _ o m n associationlikemangledmodelsIDs,orexceptionsaboutconflictingIDschances areyouforgotthatbit.

3.4ControllingAssociationScope
Bydefault,associationslookforobjectsonlywithinthecurrentmodule sscope.ThiscanbeimportantwhenyoudeclareActiveRecordmodelswithina module.Forexample:

mdl oue MApiain yplcto mdl oue Bsns uies cas ls Splecieeod:ae upir<AtvRcr:Bs hsoe a_n :c ac ed n cas ls Acut<AtvRcr:Bs concieeod:ae blnst eog_o : i e ed n

ed n ed n ed n

Thiswillworkfine,becauseboththeS p l e andtheA c u t upir c o n classaredefinedwithinthesamescope.Butthefollowingwillnotwork,because


S p l e andA c u t upir c o n aredefinedindifferentscopes:

mdl oue MApiain yplcto mdl oue Bsns uies cas ls Splecieeod:ae upir<AtvRcr:Bs hsoe a_n :c ac ed n ed n mdl oue Blig iln cas ls Acut<AtvRcr:Bs concieeod:ae blnst eog_o : i e ed n ed n ed n

Toassociateamodelwithamodelinadifferentnamespace,youmustspecifythecompleteclassnameinyourassociationdeclaration:

mdl oue MApiain yplcto mdl oue Bsns uies cas ls Splecieeod:ae upir<AtvRcr:Bs hsoe a_n :c ac , : a _ae c = > " Apiain:iln:Acut M plcto:Blig:con" ed n

ed n mdl oue Blig iln cas ls Acut<AtvRcr:Bs concieeod:ae blnst eog_o : i e , : a _ae c = > " Apiain:uies:upir M plcto:Bsns:Sple" ed n ed n ed n

4DetailedAssociationReference
Thefollowingsectionsgivethedetailsofeachtypeofassociation,includingthemethodsthattheyaddandtheoptionsthatyoucanusewhendeclaring anassociation.

4.1b e

g _ AssociationReference

Theb l n s t associationcreatesaonetoonematchwithanothermodel.Indatabaseterms,thisassociationsaysthatthisclasscontainsthe eog_o foreignkey.Iftheotherclasscontainstheforeignkey,thenyoushoulduseh s o e a _ n instead. 4.1.1MethodsAddedbyb e g_

Whenyoudeclareab l n s t association,thedeclaringclassautomaticallygainsfourmethodsrelatedtotheassociation: eog_o ascainfrerlaas) soito(oc_eod=fle ascain(soit) soito=ascae


bidascainatiue} ul_soito(trbts={) cet_soito(trbts={) raeascainatiue}

Inallofthesemethods,a s c a i n s o i t o isreplacedwiththesymbolpassedasthefirstargumenttob l n s t .Forexample,giventhedeclaration: eog_o

cas ls Odr<AtvRcr:Bs recieeod:ae blnst eog_o : c e ed n

Eachinstanceoftheordermodelwillhavethesemethods:

csoe utmr csoe= utmr bidcsoe ul_utmr cet_utmr raecsoe

Wheninitializinganewh s o e b l n s t associationyoumustusetheb i d prefixtobuildtheassociation,ratherthanthe a _ n or e o g _ o ul_

ascainbid s o i t o . u l methodthatwouldbeusedforh s m n orh s a d b l n s t _ a y a_ay a _ n _ e o g _ o m n associations.Tocreateone,usethec e t _ rae

prefix. 4.1.1.1a s c a i n f r e r l a a s ) soito(oc_eod=fle Thea s c a i n s o i t o methodreturnstheassociatedobject,ifany.Ifnoassociatedobjectisfound,itreturnsn l i.

@ c e = @ d e .utmr csoe

Iftheassociatedobjecthasalreadybeenretrievedfromthedatabaseforthisobject,thecachedversionwillbereturned.Tooverridethisbehavior(and forceadatabaseread),passt u asthef r e r l a argument. re oc_eod 4.1.1.2a s c a i n ( s o i t ) soito=ascae Thea s c a i n methodassignsanassociatedobjecttothisobject.Behindthescenes,thismeansextractingtheprimarykeyfromtheassociate soito= objectandsettingthisobject sforeignkeytothesamevalue.

@ d e .utmr= csoe @ c e

4.1.1.3b i d a s c a i n a t i u e } ul_soito(trbts={) Theb i d a s c a i n u l _ s o i t o methodreturnsanewobjectoftheassociatedtype.Thisobjectwillbeinstantiatedfromthepassedattributes,andthelink throughthisobject sforeignkeywillbeset,buttheassociatedobjectwillnotyetbesaved.

@ c e = @ d e .ul_utmr bidcsoe( : c e_ b e = > 13 2 , : c e_ae = > "onDe Jho" )

4.1.1.4c e t _ s o i t o ( t r b t s = { ) raeascainatiue} Thec e t _ s o i t o methodreturnsanewobjectoftheassociatedtype.Thisobjectwillbeinstantiatedfromthepassedattributes,andthe raeascain linkthroughthisobject sforeignkeywillbeset.Inaddition,theassociatedobjectwillbesaved(assumingthatitpassesanyvalidations).

@ c e = @ d e .raecsoe( cet_utmr : c e_ b e = > 13 2 ,


: c

e_ae

: c e_ae = > "onDe Jho" )

4.1.2Optionsforb e

g_

Inmanysituations,youcanusethedefaultbehaviorofb l n s t withoutanycustomization.ButdespiteRails emphasisofconventionover eog_o customization,youcanalterthatbehaviorinanumberofways.Thissectioncoverstheoptionsthatyoucanpasswhenyoucreateab l n s t eog_o association.Forexample,anassociationwithseveraloptionsmightlooklikethis:

cas ls Odr<AtvRcr:Bs recieeod:ae blnst eog_o : c e , : c e_ah cce = > tu re , : d i c i = > "cie=1 atv" ed n

Theb l n s t associationsupportstheseoptions: eog_o


:uoae atsv :ls_ae casnm :odtos cniin :one_ah cutrcce :eedn dpnet :oeg_e frinky :nld icue :oyopi plmrhc :edny raol :eet slc :oc tuh :aiae vldt

4.1.2.1: u o a e atsv Ifyousetthe: u o a e a t s v optiontot u ,Railswillsaveanyloadedmembersanddestroymembersthataremarkedfordestructionwheneveryou re savetheparentobject. 4.1.2.2: l s _ a e casnm Ifthenameoftheothermodelcannotbederivedfromtheassociationname,youcanusethe: l s _ a e c a s n m optiontosupplythemodelname.For example,ifanorderbelongstoacustomer,buttheactualnameofthemodelcontainingcustomersisP t o ,you dsetthingsupthisway: arn

cas ls Odr<AtvRcr:Bs recieeod:ae blnst eog_o : c e ,

: a _ae c

= > "arn Pto" ed n

4.1.2.3: o d t o s cniin The: o d t o s c n i i n optionletsyouspecifytheconditionsthattheassociatedobjectmustmeet(inthesyntaxusedbyanSQLW E E H R clause).

cas ls Odr<AtvRcr:Bs recieeod:ae blnst eog_o : c e , : d i c i = > "cie=1 atv" ed n

4.1.2.4: o n e _ a h cutrcce The: o n e _ a h optioncanbeusedtomakefindingthenumberofbelongingobjectsmoreefficient.Considerthesemodels: cutrcce

cas ls Odr<AtvRcr:Bs recieeod:ae blnst eog_o : c e ed n cas ls Csoecieeod:ae utmr<AtvRcr:Bs hsmn a_ay : d e ed n

Withthesedeclarations,askingforthevalueof@ u t m r o d r . i e c s o e . r e s s z requiresmakingacalltothedatabasetoperformaC U T * query.To ON() avoidthiscall,youcanaddacountercachetothebelongingmodel:

cas ls Odr<AtvRcr:Bs recieeod:ae blnst eog_o : c e , : c e_ah cce = > tu re ed n cas ls Csoecieeod:ae utmr<AtvRcr:Bs hsmn a_ay : d e ed n

Withthisdeclaration,Railswillkeepthecachevalueuptodate,andthenreturnthatvalueinresponsetothes z method. ie

Althoughthe: o n e _ a h optionisspecifiedonthemodelthatincludestheb l n s t declaration,theactualcolumnmustbeaddedtothe cutrcce eog_o associatedmodel.Inthecaseabove,youwouldneedtoaddacolumnnamedo d r _ o n totheC s o e model.Youcanoverridethedefault rescut utmr columnnameifyouneedto:

cas ls Odr<AtvRcr:Bs recieeod:ae blnst eog_o : c e , : c e_ah cce = > : c _f d _ e ed n cas ls Csoecieeod:ae utmr<AtvRcr:Bs hsmn a_ay : d e ed n

Countercachecolumnsareaddedtothecontainingmodel slistofreadonlyattributesthrougha t _ e d n y trraol. 4.1.2.5: e e d n dpnet Ifyousetthe: e e d n optionto: e t o ,thendeletingthisobjectwillcallthed s r y dpnet dsry e t o methodontheassociatedobjecttodeletethatobject. Ifyousetthe: e e d n optionto: e e e dpnet d l t ,thendeletingthisobjectwilldeletetheassociatedobjectwithoutcallingitsd s r y e t o method.

Youshouldnotspecifythisoptiononab l n s t associationthatisconnectedwithah s m n associationontheotherclass.Doing eog_o a_ay socanleadtoorphanedrecordsinyourdatabase.

4.1.2.6: o e g _ e frinky Byconvention,Railsguessesthatthecolumnusedtoholdtheforeignkeyonthismodelisthenameoftheassociationwiththesuffix_ d i added.The


: o e g _ e optionletsyousetthenameoftheforeignkeydirectly: frinky

cas ls Odr<AtvRcr:Bs recieeod:ae blnst eog_o : c e , : a _ae c = > "arn Pto" , : eg_e f i = > "arni" pto_d ed n

Inanycase,Railswillnotcreateforeignkeycolumnsforyou.Youneedtoexplicitlydefinethemaspartofyourmigrations.

4.1.2.7: n l d icue

Youcanusethe: n l d optiontospecifysecondorderassociationsthatshouldbeeagerloadedwhenthisassociationisused.Forexample, icue considerthesemodels:

cas ls LnIecieeod:ae ietm<AtvRcr:Bs blnst eog_o : d e ed n cas ls Odr<AtvRcr:Bs recieeod:ae blnst eog_o : c e hsmn a_ay :ieie _ ed n cas ls Csoecieeod:ae utmr<AtvRcr:Bs hsmn a_ay : d e ed n

Ifyoufrequentlyretrievecustomersdirectlyfromlineitems(@ i e i e . r e . u t m r l n _ t m o d r c s o e ),thenyoucanmakeyourcodesomewhatmoreefficient byincludingcustomersintheassociationfromlineitemstoorders:

cas ls LnIecieeod:ae ietm<AtvRcr:Bs blnst eog_o : d e , : c d i e = > : c e ed n cas ls Odr<AtvRcr:Bs recieeod:ae blnst eog_o : c e hsmn a_ay :ieie _ ed n cas ls Csoecieeod:ae utmr<AtvRcr:Bs hsmn a_ay : d e ed n

There snoneedtouse: n l d forimmediateassociationsthatis,ifyouhaveO d r b l n s t c s o e ,thenthecustomeriseager icue reeog_o:utmr loadedautomaticallywhenit sneeded.

4.1.2.8: o y o p i plmrhc Passingt u tothe: o y o p i optionindicatesthatthisisapolymorphicassociation.Polymorphicassociationswerediscussedindetailearlier re plmrhc inthisguide. 4.1.2.9: e d n y raol Ifyousetthe: e d n y r a o l optiontot u ,thentheassociatedobjectwillbereadonlywhenretrievedviatheassociation. re 4.1.2.10: e e t slc The: e e t s l c optionletsyouoverridetheSQLS L C clausethatisusedtoretrievedataabouttheassociatedobject.Bydefault,Railsretrievesall EET columns. Ifyousetthe: e e t s l c optiononab l n s t association,youshouldalsosetthef r i n k y eog_o o e g _ e optiontoguaranteethecorrectresults. 4.1.2.11: o c tuh Ifyousetthe: o c optionto: r e tuh t u ,thentheu d t d a oru d t d o timestampontheassociatedobjectwillbesettothecurrenttime pae_t pae_n wheneverthisobjectissavedordestroyed:

cas ls Odr<AtvRcr:Bs recieeod:ae blnst eog_o : c e , : c h = > tu re ed n cas ls Csoecieeod:ae utmr<AtvRcr:Bs hsmn a_ay : d e ed n

Inthiscase,savingordestroyinganorderwillupdatethetimestampontheassociatedcustomer.Youcanalsospecifyaparticulartimestampattribute toupdate:

cas ls Odr<AtvRcr:Bs recieeod:ae blnst eog_o : c e , : c h = > : d _ d e_ e a da ed n

4.1.2.12: a i a e vldt Ifyousetthe: a i a e v l d t optiontot u ,thenassociatedobjectswillbevalidatedwheneveryousavethisobject.Bydefault,thisisf l e re as: associatedobjectswillnotbevalidatedwhenthisobjectissaved. 4.1.3HowToKnowWhetherThere sanAssociatedObject? Toknowwhetherthere sandassociatedobjectjustchecka s c a i n n l : soito.i?

i f @ d e .utmr csoe. nl i ? @ g = "ocsoeonohsodr Nutmrfudfrtire" ed n

4.1.4WhenareObjectsSaved? Assigninganobjecttoab l n s t associationdoesnotautomaticallysavetheobject.Itdoesnotsavetheassociatedobjecteither. eog_o

4.2h _ e a AssociationReference
Theh s o e a _ n associationcreatesaonetoonematchwithanothermodel.Indatabaseterms,thisassociationsaysthattheotherclasscontainsthe foreignkey.Ifthisclasscontainstheforeignkey,thenyoushoulduseb l n s t instead. eog_o 4.2.1MethodsAddedbyh _ e a Whenyoudeclareah s o e a _ n association,thedeclaringclassautomaticallygainsfourmethodsrelatedtotheassociation: ascainfrerlaas) soito(oc_eod=fle ascain(soit) soito=ascae
bidascainatiue} ul_soito(trbts={) cet_soito(trbts={) raeascainatiue}

Inallofthesemethods,a s c a i n s o i t o isreplacedwiththesymbolpassedasthefirstargumenttoh s o e a _ n .Forexample,giventhedeclaration:

cas ls Splecieeod:ae upir<AtvRcr:Bs hsoe a_n :c ac ed n

EachinstanceoftheS p l e modelwillhavethesemethods: upir

acut con acut con= bidacut ul_con cet_con raeacut

Wheninitializinganewh s o e b l n s t associationyoumustusetheb i d prefixtobuildtheassociation,ratherthanthe a _ n or e o g _ o ul_


ascainbid s o i t o . u l methodthatwouldbeusedforh s m n orh s a d b l n s t _ a y a_ay a _ n _ e o g _ o m n associations.Tocreateone,usethec e t _ rae

prefix. 4.2.1.1a s c a i n f r e r l a a s ) soito(oc_eod=fle Thea s c a i n s o i t o methodreturnstheassociatedobject,ifany.Ifnoassociatedobjectisfound,itreturnsn l i.

@c ac
= @

i e

@ i e .con acut

Iftheassociatedobjecthasalreadybeenretrievedfromthedatabaseforthisobject,thecachedversionwillbereturned.Tooverridethisbehavior(and forceadatabaseread),passt u asthef r e r l a argument. re oc_eod 4.2.1.2a s c a i n ( s o i t ) soito=ascae Thea s c a i n methodassignsanassociatedobjecttothisobject.Behindthescenes,thismeansextractingtheprimarykeyfromthisobjectand soito= settingtheassociateobject sforeignkeytothesamevalue.

@ i e .con acut= @c ac

4.2.1.3b i d a s c a i n a t i u e } ul_soito(trbts={) Theb i d a s c a i n u l _ s o i t o methodreturnsanewobjectoftheassociatedtype.Thisobjectwillbeinstantiatedfromthepassedattributes,andthelink throughitsforeignkeywillbeset,buttheassociatedobjectwillnotyetbesaved.

@c ac = @ i e .ul_con( bidacut :e = > "e0 Nt3" )

4.2.1.4c e t _ s o i t o ( t r b t s = { ) raeascainatiue} Thec e t _ s o i t o methodreturnsanewobjectoftheassociatedtype.Thisobjectwillbeinstantiatedfromthepassedattributes,andthe raeascain linkthroughitsforeignkeywillbeset.Inaddition,theassociatedobjectwillbesaved(assumingthatitpassesanyvalidations).

@c ac = @ i e .raeacut cet_con( :e = > "e0 Nt3" )

4.2.2Optionsforh _ e a Inmanysituations,youcanusethedefaultbehaviorofh s o e a _ n withoutanycustomization.ButdespiteRails emphasisofconventionover customization,youcanalterthatbehaviorinanumberofways.Thissectioncoverstheoptionsthatyoucanpasswhenyoucreateah s o e a_n association.Forexample,anassociationwithseveraloptionsmightlooklikethis:

cas ls Splecieeod:ae upir<AtvRcr:Bs hsoe a_n :c ac , : a _ae c = >

= > "iln" Blig , :eed d e = > : i f ed n

Theh s o e a _ n associationsupportstheseoptions:
:s a :uoae atsv :ls_ae casnm :odtos cniin :eedn dpnet :oeg_e frinky :nld icue :re odr :rmr_e piayky :edny raol :eet slc :ore suc :oretp suc_ye :hog truh :aiae vldt

4.2.2.1: s a Settingthe: s a optionindicatesthatthisisapolymorphicassociation.Polymorphicassociationswerediscussedindetailearlierinthisguide. 4.2.2.2: u o a e atsv Ifyousetthe: u o a e a t s v optiontot u ,Railswillsaveanyloadedmembersanddestroymembersthataremarkedfordestructionwheneveryou re savetheparentobject. 4.2.2.3: l s _ a e casnm Ifthenameoftheothermodelcannotbederivedfromtheassociationname,youcanusethe: l s _ a e c a s n m optiontosupplythemodelname.For example,ifasupplierhasanaccount,buttheactualnameofthemodelcontainingaccountsisB l i g i l n ,you dsetthingsupthisway:

cas ls Splecieeod:ae upir<AtvRcr:Bs hsoe a_n :c ac , : a _ae c = > "iln" Blig ed n

4.2.2.4: o d t o s cniin The: o d t o s c n i i n optionletsyouspecifytheconditionsthattheassociatedobjectmustmeet(inthesyntaxusedbyanSQLW E E H R clause).

cas ls Splecieeod:ae upir<AtvRcr:Bs hsoe a_n :c ac ,

, : d i c i = > "ofre" cnimd=1 ed n

4.2.2.5: e e d n dpnet Ifyousetthe: e e d n optionto: e t o ,thendeletingthisobjectwillcallthed s r y dpnet dsry e t o methodontheassociatedobjecttodeletethatobject. Ifyousetthe: e e d n optionto: e e e dpnet d l t ,thendeletingthisobjectwilldeletetheassociatedobjectwithoutcallingitsd s r y e t o method.Ifyou setthe: e e d n optionto: u l f ,thendeletingthisobjectwillsettheforeignkeyintheassociationobjecttoN L . dpnet nliy UL 4.2.2.6: o e g _ e frinky Byconvention,Railsguessesthatthecolumnusedtoholdtheforeignkeyontheothermodelisthenameofthismodelwiththesuffix_ d i added.The
: o e g _ e optionletsyousetthenameoftheforeignkeydirectly: frinky

cas ls Splecieeod:ae upir<AtvRcr:Bs hsoe a_n :c ac , : eg_e f i = > "upi" sp_d ed n

Inanycase,Railswillnotcreateforeignkeycolumnsforyou.Youneedtoexplicitlydefinethemaspartofyourmigrations. 4.2.2.7: n l d icue Youcanusethe: n l d optiontospecifysecondorderassociationsthatshouldbeeagerloadedwhenthisassociationisused.Forexample, icue considerthesemodels:

cas ls Splecieeod:ae upir<AtvRcr:Bs hsoe a_n :c ac ed n cas ls Acut<AtvRcr:Bs concieeod:ae blnst eog_o : i e blnst eog_o :e ee aie ed n cas ls Rpeettvcieeod:ae ersnaie<AtvRcr:Bs hsmn a_ay :c ac ed n

Ifyoufrequentlyretrieverepresentativesdirectlyfromsuppliers(@ u p i r a c u t r p e e t t v ),thenyoucanmakeyourcodesomewhat sple.con.ersnaie moreefficientbyincludingrepresentativesintheassociationfromsupplierstoaccounts:

moreefficientbyincludingrepresentativesintheassociationfromsupplierstoaccounts:

cas ls Splecieeod:ae upir<AtvRcr:Bs hsoe a_n :c ac , : c d i e = > :e ee aie ed n cas ls Acut<AtvRcr:Bs concieeod:ae blnst eog_o : i e blnst eog_o :e ee aie ed n cas ls Rpeettvcieeod:ae ersnaie<AtvRcr:Bs hsmn a_ay :c ac ed n

4.2.2.8: r e odr The: r e optiondictatestheorderinwhichassociatedobjectswillbereceived(inthesyntaxusedbyanSQLO D R B clause).Becausea odr REY


hsoe a _ n associationwillonlyretrieveasingleassociatedobject,thisoptionshouldnotbeneeded.

4.2.2.9: r m r _ e piayky Byconvention,Railsguessesthatthecolumnusedtoholdtheprimarykeyofthismodelisi .Youcanoverridethisandexplicitlyspecifytheprimary d keywiththe: r m r _ e option. piayky 4.2.2.10: e d n y raol Ifyousetthe: e d n y r a o l optiontot u ,thentheassociatedobjectwillbereadonlywhenretrievedviatheassociation. re 4.2.2.11: e e t slc The: e e t s l c optionletsyouoverridetheSQLS L C clausethatisusedtoretrievedataabouttheassociatedobject.Bydefault,Railsretrievesall EET columns. 4.2.2.12: o r e suc The: o r e s u c optionspecifiesthesourceassociationnameforah s o e : h o g association. a_ntruh 4.2.2.13: o r e t p suc_ye The: o r e t p optionspecifiesthesourceassociationtypeforah s o e : h o g associationthatproceedsthroughapolymorphic suc_ye a_ntruh association. 4.2.2.14: h o g truh The: h o g optionspecifiesajoinmodelthroughwhichtoperformthequery.h s o e : h o g associationswerediscussedindetailearlierin truh a_ntruh thisguide.

4.2.2.15: a i a e vldt Ifyousetthe: a i a e v l d t optiontot u ,thenassociatedobjectswillbevalidatedwheneveryousavethisobject.Bydefault,thisisf l e re as:

Ifyousetthe: a i a e v l d t optiontot u ,thenassociatedobjectswillbevalidatedwheneveryousavethisobject.Bydefault,thisisf l e re as: associatedobjectswillnotbevalidatedwhenthisobjectissaved. 4.2.3HowToKnowWhetherThere sanAssociatedObject? Toknowwhetherthere sandassociatedobjectjustchecka s c a i n n l : soito.i?

i f @ i e .con. acut nl i ? @ g = "oacutfudfrtiupir Ncononohssple" ed n

4.2.4WhenareObjectsSaved? Whenyouassignanobjecttoah s o e a _ n association,thatobjectisautomaticallysaved(inordertoupdateitsforeignkey).Inaddition,anyobject beingreplacedisalsoautomaticallysaved,becauseitsforeignkeywillchangetoo. Ifeitherofthesesavesfailsduetovalidationerrors,thentheassignmentstatementreturnsf l e a s andtheassignmentitselfiscancelled. Iftheparentobject(theonedeclaringtheh s o e a _ n association)isunsaved(thatis,n w r c r ? e _ e o d returnst u )thenthechildobjectsarenotsaved. re Theywillautomaticallywhentheparentobjectissaved. Ifyouwanttoassignanobjecttoah s o e a _ n associationwithoutsavingtheobject,usethea s c a i n b i d s o i t o . u l method.

4.3h _ a AssociationReference a
Theh s m n associationcreatesaonetomanyrelationshipwithanothermodel.Indatabaseterms,thisassociationsaysthattheotherclasswill a_ay haveaforeignkeythatreferstoinstancesofthisclass. 4.3.1MethodsAddedbyh _ a a Whenyoudeclareah s m n association,thedeclaringclassautomaticallygains13methodsrelatedtotheassociation: a_ay cleto(oc_eod=fle olcinfrerlaas) cleto<(bet) olcin<ojc, cleto.eeeojc, ) olcindlt(bet cleto=bet olcinojcs cleto_iglris olcinsnua_d cleto_iglrisis olcinsnua_d=d cleto.la olcincer cleto.mt? olcinepy cleto.ie olcinsz cleto.id ) olcinfn( cleto.hr() olcinwee cleto.xss() olcineit? cleto.ul(trbts={, ) olcinbidatiue} cleto.raeatiue} olcincet(trbts={) Inallofthesemethods,c l e t o isreplacedwiththesymbolpassedasthefirstargumenttoh s m n ,andc l e t o _ i g l r olcin a_ay o l c i n s n u a is replacedwiththesingularizedversionofthatsymbol..Forexample,giventhedeclaration:

cas ls Csoecieeod:ae utmr<AtvRcr:Bs

Csoecieeod:ae utmr<AtvRcr:Bs hsmn a_ay : d e ed n

Eachinstanceofthecustomermodelwillhavethesemethods:

odr(oc_eod= resfrerla fle as ) odr<(bet.) res<ojc,.. odr.eeeojc,.. resdlt(bet.) odr=bet resojcs odris re_d odrisis re_d=d odr.la rescer odr.mt? resepy odr.ie ressz odr.id.. resfn(.) odr.hr(.) reswee.. odr.xss(.) reseit?.. odr.ul(trbts={,.. resbidatiue}.) odr.raeatiue} rescet(trbts={)

4.3.1.1c l e t o ( o c _ e o d = f l e olcinfrerlaas) Thec l e t o methodreturnsanarrayofalloftheassociatedobjects.Iftherearenoassociatedobjects,itreturnsanemptyarray. olcin

@ d e = @ c e .res odr

4.3.1.2c l e t o < ( b e t ) olcin<ojc, Thec l e t o < methodaddsoneormoreobjectstothecollectionbysettingtheirforeignkeystotheprimarykeyofthecallingmodel. olcin<

@ c e .res< odr< @ d 1 e

4.3.1.3c l e t o . e e e o j c , ) olcindlt(bet Thec l e t o . e e e o l c i n d l t methodremovesoneormoreobjectsfromthecollectionbysettingtheirforeignkeystoN L . UL

@ c e .resdlt( odr.eee @ d 1 e )

Additionally,objectswillbedestroyedifthey reassociatedwith: e e d n > : e t o ,anddeletedifthey reassociatedwith dpnet=dsry


:eedn>:eeeal dpnet=dlt_l.

4.3.1.4c l e t o = b e t olcinojcs Thec l e t o = o l c i n methodmakesthecollectioncontainonlythesuppliedobjects,byaddinganddeletingasappropriate.

4.3.1.5c l e t o _ i g l r i s olcinsnua_d Thec l e t o _ i g l r i s o l c i n s n u a _ d methodreturnsanarrayoftheidsoftheobjectsinthecollection.

@ d _d e i = @ c e .re_d odris

4.3.1.6c l e t o _ i g l r i s i s olcinsnua_d=d Thec l e t o _ i g l r i s methodmakesthecollectioncontainonlytheobjectsidentifiedbythesuppliedprimarykeyvalues,byaddingand olcinsnua_d= deletingasappropriate. 4.3.1.7c l e t o . l a olcincer Thec l e t o . l a methodremoveseveryobjectfromthecollection.Thisdestroystheassociatedobjectsiftheyareassociatedwith olcincer
: e e d n > : e t o ,deletesthemdirectlyfromthedatabaseif: e e d n > : e e e a l dpnet=dsry d p n e t = d l t _ l ,andotherwisesetstheirforeignkeysto NL. UL

4.3.1.8c l e t o . m t ? olcinepy Thec l e t o . m t ? o l c i n e p y methodreturnst u ifthecollectiondoesnotcontainanyassociatedobjects. re

< % i f @ c e .resepy> odr.mt?% NresFud oOdron < % ed n % >

4.3.1.9c l e t o . i e olcinsz Thec l e t o . i e o l c i n s z methodreturnsthenumberofobjectsinthecollection.

@ d _ e c = @ c e .ressz odr.ie

4.3.1.10c l e t o . i d ) olcinfn( Thec l e t o . i d o l c i n f n methodfindsobjectswithinthecollection.ItusesthesamesyntaxandoptionsasA t v R c r : B s . i d cieeod:aefn.

@ e_ d e = @ c e .reswee odr.hr( : e = > 1 )

4.3.1.11c l e t o . h r ( ) olcinwee

4.3.1.11c l e t o . h r ( ) olcinwee Thec l e t o . h r methodfindsobjectswithinthecollectionbasedontheconditionssuppliedbuttheobjectsareloadedlazilymeaningthatthe olcinwee databaseisqueriedonlywhentheobject(s)areaccessed.

@ e_ d e = @ c e .reswee odr.hr( : e = > tu re ) #Nure oqeyyt @ e_ d e = @ e_ d e .is frt #Nwtedtbsilbure ohaaaewleqeid

4.3.1.12c l e t o . x s s ( ) olcineit? Thec l e t o . x s s methodcheckswhetheranobjectmeetingthesuppliedconditionsexistsinthecollection.Itusesthesamesyntaxand olcineit? optionsasA t v R c r : B s . x s s . cieeod:aeeit? 4.3.1.13c l e t o . u l ( t r b t s = { , ) olcinbidatiue} Thec l e t o . u l methodreturnsoneormorenewobjectsoftheassociatedtype.Theseobjectswillbeinstantiatedfromthepassed olcinbid attributes,andthelinkthroughtheirforeignkeywillbecreated,buttheassociatedobjectswillnotyetbesaved.

@ d e = @ c e .resbid odr.ul( : d _ae e d = > Tm ie .o, nw : d _ b e e = > "135 A24" )

4.3.1.14c l e t o . r a e a t i u e } olcincet(trbts={) Thec l e t o . r a e o l c i n c e t methodreturnsanewobjectoftheassociatedtype.Thisobjectwillbeinstantiatedfromthepassedattributes,thelink throughitsforeignkeywillbecreated,andtheassociatedobjectwillbesaved(assumingthatitpassesanyvalidations).

@ d e = @ c e .rescet( odr.rae : d _ae e d = > Tm ie .o, nw


: d _ e

b e

= > "135 A24" )

4.3.2Optionsforh _ a a Inmanysituations,youcanusethedefaultbehaviorforh s m n withoutanycustomization.Butyoucanalterthatbehaviorinanumberofways. a_ay Thissectioncoverstheoptionsthatyoucanpasswhenyoucreateah s m n association.Forexample,anassociationwithseveraloptionsmight a_ay looklikethis:

cas ls Csoecieeod:ae utmr<AtvRcr:Bs hsmn a_ay : d e , :eed d e = > :eeea d _ , :aiae d = > :a e f ed n

Theh s m n associationsupportstheseoptions: a_ay


:s a :uoae atsv :ls_ae casnm :odtos cniin :one_q cutrsl :eedn dpnet :xed etn :idrsl fne_q :oeg_e frinky :ru gop :nld icue :ii lmt :fst ofe :re odr :rmr_e piayky :edny raol :eet slc :ore suc :oretp suc_ye :hog truh :nq ui :aiae vldt

4.3.2.1: s a Settingthe: s a optionindicatesthatthisisapolymorphicassociation,asdiscussedearlierinthisguide. 4.3.2.2: u o a e atsv Ifyousetthe: u o a e a t s v optiontot u ,Railswillsaveanyloadedmembersanddestroymembersthataremarkedfordestructionwheneveryou re savetheparentobject.

4.3.2.3: l s _ a e casnm Ifthenameoftheothermodelcannotbederivedfromtheassociationname,youcanusethe: l s _ a e c a s n m optiontosupplythemodelname.For example,ifacustomerhasmanyorders,buttheactualnameofthemodelcontainingordersisT a s c i n r n a t o ,you dsetthingsupthisway:

cas ls Csoecieeod:ae utmr<AtvRcr:Bs hsmn a_ay : d e , : a _ae c = > "rnato" Tascin ed n

4.3.2.4: o d t o s cniin The: o d t o s c n i i n optionletsyouspecifytheconditionsthattheassociatedobjectmustmeet(inthesyntaxusedbyanSQLW E E H R clause).

cas ls Csoecieeod:ae utmr<AtvRcr:Bs hsmn a_ay : f e_ d c i d e , : a _ae c = > "re" Odr , : d i c i = > "ofre" cnimd=1 ed n

Youcanalsosetconditionsviaahash:

cas ls Csoecieeod:ae utmr<AtvRcr:Bs hsmn a_ay : f e_ d c i d e , : a _ae c = > "re" Odr , : d i c i = >{ : f e c i d = > tu re } ed n

Ifyouuseahashstyle: o d t o s c n i i n option,thenrecordcreationviathisassociationwillbeautomaticallyscopedusingthehash.Inthiscase,using
@ u t m r c n i m d o d r . r a e @ u t m r c n i m d o d r . u l willcreateorderswheretheconfirmedcolumnhasthe c s o e . o f r e _ r e s c e t or c s o e . o f r e _ r e s b i d

valuet u . re Ifyouneedtoevaluateconditionsdynamicallyatruntime,useaproc:

cas ls Csoecieeod:ae utmr<AtvRcr:Bs hsmn a_ay :ae _ d e , : a _ae c = > "re" Odr , : d i c i =rc{[odr.rae_t>? >po"rescetda, 1 0 .or.g]} husao ed n

4.3.2.5: o n e _ q cutrsl NormallyRailsautomaticallygeneratestheproperSQLtocounttheassociationmembers.Withthe: o n e _ q option,youcanspecifya cutrsl completeSQLstatementtocountthemyourself. Ifyouspecify: i d r s l f n e _ q butnot: o n e _ q ,thenthecounterSQLwillbegeneratedbysubstitutingS L C O N ( ) F O forthe cutrsl EETCUT*RM
SLC.RM E E T . . F O clauseofyour: i d r s l f n e _ q statement.

4.3.2.6: e e d n dpnet Ifyousetthe: e e d n optionto: e t o ,thendeletingthisobjectwillcallthed s r y dpnet dsry e t o methodontheassociatedobjectstodeletethose objects.Ifyousetthe: e e d n optionto: e e e a l dpnet d l t _ l ,thendeletingthisobjectwilldeletetheassociatedobjectswithoutcallingtheird s r y eto method.Ifyousetthe: e e d n optionto: u l f ,thendeletingthisobjectwillsettheforeignkeyintheassociatedobjectstoN L . dpnet nliy UL Thisoptionisignoredwhenyouusethe: h o g optionontheassociation. truh 4.3.2.7: x e d etn The: x e d e t n optionspecifiesanamedmoduletoextendtheassociationproxy.Associationextensionsarediscussedindetaillaterinthisguide. 4.3.2.8: i d r s l fne_q NormallyRailsautomaticallygeneratestheproperSQLtofetchtheassociationmembers.Withthe: i d r s l f n e _ q option,youcanspecifyacomplete SQLstatementtofetchthemyourself.IffetchingobjectsrequirescomplexmultitableSQL,thismaybenecessary. 4.3.2.9: o e g _ e frinky Byconvention,Railsguessesthatthecolumnusedtoholdtheforeignkeyontheothermodelisthenameofthismodelwiththesuffix_ d i added.The
: o e g _ e optionletsyousetthenameoftheforeignkeydirectly: frinky

cas ls Csoecieeod:ae utmr<AtvRcr:Bs hsmn a_ay : d e , : eg_e f i

= > "uti" cs_d ed n

Inanycase,Railswillnotcreateforeignkeycolumnsforyou.Youneedtoexplicitlydefinethemaspartofyourmigrations. 4.3.2.10: r u gop The: r u optionsuppliesanattributenametogrouptheresultsetby,usingaG O P B clauseinthefinderSQL. gop RUY

cas ls Csoecieeod:ae utmr<AtvRcr:Bs hsmn a_ay :ieie _ , :h g h = > : d e , : g = > "resi" odr.d ed n

4.3.2.11: n l d icue Youcanusethe: n l d optiontospecifysecondorderassociationsthatshouldbeeagerloadedwhenthisassociationisused.Forexample, icue considerthesemodels:

cas ls Csoecieeod:ae utmr<AtvRcr:Bs hsmn a_ay : d e ed n cas ls Odr<AtvRcr:Bs recieeod:ae blnst eog_o : c e hsmn a_ay :ieie _ ed n cas ls LnIecieeod:ae ietm<AtvRcr:Bs blnst eog_o : d e ed n

Ifyoufrequentlyretrievelineitemsdirectlyfromcustomers(@ u t m r o d r . i e i e s c s o e . r e s l n _ t m ),thenyoucanmakeyourcodesomewhatmore efficientbyincludinglineitemsintheassociationfromcustomerstoorders:


cas ls Csoecieeod:ae utmr<AtvRcr:Bs

Csoecieeod:ae utmr<AtvRcr:Bs hsmn a_ay : d e , : c d i e = > :ieie _ ed n cas ls Odr<AtvRcr:Bs recieeod:ae blnst eog_o : c e hsmn a_ay :ieie _ ed n cas ls LnIecieeod:ae ietm<AtvRcr:Bs blnst eog_o : d e ed n

4.3.2.12: i i lmt The: i i optionletsyourestrictthetotalnumberofobjectsthatwillbefetchedthroughanassociation. lmt

cas ls Csoecieeod:ae utmr<AtvRcr:Bs hsmn a_ay :ee _ d c e , : a _ae c = > "re" Odr , : d e = > "re_aeDS" odrdtEC , :ii = > 10 0 ed n

4.3.2.13: f s t ofe The: f s t o f e optionletsyouspecifythestartingoffsetforfetchingobjectsviaanassociation.Forexample,ifyouset: f s t = 1 o f e > 1 ,itwillskip thefirst11records. 4.3.2.14: r e odr The: r e optiondictatestheorderinwhichassociatedobjectswillbereceived(inthesyntaxusedbyanSQLO D R B clause). odr REY

cas ls Csoecieeod:ae utmr<AtvRcr:Bs

Csoecieeod:ae utmr<AtvRcr:Bs hsmn a_ay : d e , : d e = > "aecnimdDS" dt_ofreEC ed n

4.3.2.15: r m r _ e piayky Byconvention,Railsguessesthatthecolumnusedtoholdtheprimarykeyoftheassociationisi .Youcanoverridethisandexplicitlyspecifythe d primarykeywiththe: r m r _ e option. piayky 4.3.2.16: e d n y raol Ifyousetthe: e d n y r a o l optiontot u ,thentheassociatedobjectswillbereadonlywhenretrievedviatheassociation. re 4.3.2.17: e e t slc The: e e t s l c optionletsyouoverridetheSQLS L C clausethatisusedtoretrievedataabouttheassociatedobjects.Bydefault,Railsretrievesall EET columns.

Ifyouspecifyyourown: e e t s l c ,besuretoincludetheprimarykeyandforeignkeycolumnsoftheassociatedmodel.Ifyoudonot,Rails willthrowanerror.

4.3.2.18: o r e suc The: o r e s u c optionspecifiesthesourceassociationnameforah s m n t r u h a _ a y : h o g association.Youonlyneedtousethisoptionifthenameof thesourceassociationcannotbeautomaticallyinferredfromtheassociationname. 4.3.2.19: o r e t p suc_ye The: o r e t p optionspecifiesthesourceassociationtypeforah s m n t r u h suc_ye a _ a y : h o g associationthatproceedsthroughapolymorphic association. 4.3.2.20: h o g truh The: h o g optionspecifiesajoinmodelthroughwhichtoperformthequery.h s m n t r u h truh a _ a y : h o g associationsprovideawaytoimplement manytomanyrelationships,asdiscussedearlierinthisguide. 4.3.2.21: n q ui Setthe: n q u i optiontotruetokeepthecollectionfreeofduplicates.Thisismostlyusefultogetherwiththe: h o g option. truh

cas ls Procieeod:ae esn<AtvRcr:Bs hsmn a_ay :ed g ai hsmn a_ay : , :h g h = > :ed g ai ed n proesncet( esn=Pro.rae

:ae = >

= > 'on jh' ) psotcet( ot=Ps.rae :ae = > '1 a' ) pro.ot<ps esnpss<ot pro.ot<ps esnpss<ot pro.ot.npc esnpssiset #=#Psd,nm:"1><oti:5aea"] >[<oti:5aea",#Psd,nm:"1> Raigaliset edn.l.npc #=#Raigi:1,pro_d,ps_d><ednd3esni:5oti:5] >[<ednd2esni:5oti:5,#Raigi:1,pro_d,ps_d>

Intheabovecasetherearetworeadingsandp r o . o t bringsoutbothofthemeventhoughtheserecordsarepointingtothesamepost. esnpss Nowlet sset: n q u i totrue:

cas ls Pro esn hsmn a_ay :ed g ai hsmn a_ay : , :h g h = > :ed g ai , : i = > tu re ed n proesncet( esn=Pro.rae :ae = > 'od' hna ) psotcet( ot=Ps.rae :ae = > '1 a' ) pro.ot<ps esnpss<ot pro.ot<ps esnpss<ot pro.ot.npc esnpssiset #=#Psd,nm:"1> >[<oti:7aea"] Raigaliset edn.l.npc #=#Raigi:1,pro_d,ps_d><ednd7esni:7oti:7] >[<ednd6esni:7oti:7,#Raigi:1,pro_d,ps_d>

Intheabovecasetherearestilltworeadings.Howeverp r o . o t showsonlyonepostbecausethecollectionloadsonlyuniquerecords. esnpss 4.3.2.22: a i a e vldt Ifyousetthe: a i a e v l d t optiontof l e a s ,thenassociatedobjectswillnotbevalidatedwheneveryousavethisobject.Bydefault,thisist u : re associatedobjectswillbevalidatedwhenthisobjectissaved. 4.3.3WhenareObjectsSaved? Whenyouassignanobjecttoah s m n association,thatobjectisautomaticallysaved(inordertoupdateitsforeignkey).Ifyouassignmultiple a_ay

Whenyouassignanobjecttoah s m n association,thatobjectisautomaticallysaved(inordertoupdateitsforeignkey).Ifyouassignmultiple a_ay objectsinonestatement,thentheyareallsaved. Ifanyofthesesavesfailsduetovalidationerrors,thentheassignmentstatementreturnsf l e a s andtheassignmentitselfiscancelled. Iftheparentobject(theonedeclaringtheh s m n association)isunsaved(thatis,n w r c r ? a_ay e _ e o d returnst u )thenthechildobjectsarenotsaved re whentheyareadded.Allunsavedmembersoftheassociationwillautomaticallybesavedwhentheparentissaved. Ifyouwanttoassignanobjecttoah s m n associationwithoutsavingtheobject,usethec l e t o . u l method. a_ay olcinbid

4.4h _ d b a a _e

g _ _ a AssociationReference

Theh s a d b l n s t _ a y a _ n _ e o g _ o m n associationcreatesamanytomanyrelationshipwithanothermodel.Indatabaseterms,thisassociatestwo classesviaanintermediatejointablethatincludesforeignkeysreferringtoeachoftheclasses. 4.4.1MethodsAddedbyh _ d b a a _e g_ _a

Whenyoudeclareah s a d b l n s t _ a y a _ n _ e o g _ o m n association,thedeclaringclassautomaticallygains13methodsrelatedtotheassociation: cleto(oc_eod=fle olcinfrerlaas) cleto<(bet) olcin<ojc, cleto.eeeojc, ) olcindlt(bet cleto=bet olcinojcs cleto_iglris olcinsnua_d cleto_iglrisis olcinsnua_d=d cleto.la olcincer cleto.mt? olcinepy cleto.ie olcinsz cleto.id ) olcinfn( cleto.hr() olcinwee cleto.xss() olcineit? cleto.ul(trbts={) olcinbidatiue} cleto.raeatiue} olcincet(trbts={) Inallofthesemethods,c l e t o isreplacedwiththesymbolpassedasthefirstargumenttoh s a d b l n s t _ a y olcin a _ n _ e o g _ o m n ,and cleto_iglr o l c i n s n u a isreplacedwiththesingularizedversionofthatsymbol.Forexample,giventhedeclaration:

cas ls Prcieeod:ae at<AtvRcr:Bs hsadblnst_ay a_n_eog_omn : ebi a e ed n

Eachinstanceofthepartmodelwillhavethesemethods:

asmle(oc_eod= sebisfrerla fle as ) asmle<(bet.) sebis<ojc,.. asmle.eeeojc,.. sebisdlt(bet.) asmle=bet sebisojcs asml_d sebyis asml_d=d sebyisis asmle.la sebiscer asmle.mt? sebisepy asmle.ie sebissz asmle.id.. sebisfn(.) asmle.hr(.) sebiswee.. asmle.xss(.) sebiseit?.. asmle.ul(trbts={,.. sebisbidatiue}.) asmle.raeatiue} sebiscet(trbts={)

asmle.raeatiue} sebiscet(trbts={)

4.4.1.1AdditionalColumnMethods Ifthejointableforah s a d b l n s t _ a y a _ n _ e o g _ o m n associationhasadditionalcolumnsbeyondthetwoforeignkeys,thesecolumnswillbeaddedas attributestorecordsretrievedviathatassociation.Recordsreturnedwithadditionalattributeswillalwaysbereadonly,becauseRailscannotsave changestothoseattributes.

Theuseofextraattributesonthejointableinah s a d b l n s t _ a y a _ n _ e o g _ o m n associationisdeprecated.Ifyourequirethissortofcomplex behavioronthetablethatjoinstwomodelsinamanytomanyrelationship,youshoulduseah s m n t r u h a _ a y : h o g associationinsteadof


hsadblnst_ay a_n_eog_omn.

4.4.1.2c l e t o ( o c _ e o d = f l e olcinfrerlaas) Thec l e t o methodreturnsanarrayofalloftheassociatedobjects.Iftherearenoassociatedobjects,itreturnsanemptyarray. olcin

@ ebi a e = @a .sebis asmle

4.4.1.3c l e t o < ( b e t ) olcin<ojc, Thec l e t o < methodaddsoneormoreobjectstothecollectionbycreatingrecordsinthejointable. olcin<

@a .sebis< asmle< @ eb 1 a

Thismethodisaliasedasc l e t o . o c t o l c i n c n a andc l e t o . u h olcinps. 4.4.1.4c l e t o . e e e o j c , ) olcindlt(bet Thec l e t o . e e e o l c i n d l t methodremovesoneormoreobjectsfromthecollectionbydeletingrecordsinthejointable.Thisdoesnotdestroythe objects.

@a .sebisdlt( asmle.eee @ eb 1 a )

4.4.1.5c l e t o = b e t olcinojcs Thec l e t o = o l c i n methodmakesthecollectioncontainonlythesuppliedobjects,byaddinganddeletingasappropriate. 4.4.1.6c l e t o _ i g l r i s olcinsnua_d Thec l e t o _ i g l r i s o l c i n s n u a _ d methodreturnsanarrayoftheidsoftheobjectsinthecollection.

@ eb _d a i = @a .sebyis asml_d 4.4.1.7c l e t o _ i g l r i s i s olcinsnua_d=d Thec l e t o _ i g l r i s methodmakesthecollectioncontainonlytheobjectsidentifiedbythesuppliedprimarykeyvalues,byaddingand olcinsnua_d=

Thec l e t o _ i g l r i s methodmakesthecollectioncontainonlytheobjectsidentifiedbythesuppliedprimarykeyvalues,byaddingand olcinsnua_d= deletingasappropriate. 4.4.1.8c l e t o . l a olcincer Thec l e t o . l a methodremoveseveryobjectfromthecollectionbydeletingtherowsfromthejoiningtable.Thisdoesnotdestroythe olcincer associatedobjects. 4.4.1.9c l e t o . m t ? olcinepy Thec l e t o . m t ? o l c i n e p y methodreturnst u ifthecollectiondoesnotcontainanyassociatedobjects. re

< % i f @a .sebisepy> asmle.mt?% Tiati hsprs nt o ue sd i n ayasmle nsebis < % ed n % >

4.4.1.10c l e t o . i e olcinsz Thec l e t o . i e o l c i n s z methodreturnsthenumberofobjectsinthecollection.

@ eb _ a c = @a .sebissz asmle.ie

4.4.1.11c l e t o . i d ) olcinfn( Thec l e t o . i d o l c i n f n methodfindsobjectswithinthecollection.ItusesthesamesyntaxandoptionsasA t v R c r : B s . i d c i e e o d : a e f n .Italso addstheadditionalconditionthattheobjectmustbeinthecollection.

@e_ ebi a e = @a .sebisal asmle.l( : d i c i = >[ "rae_t>? cetda" , 2 .asao) dy.g]

StartingRails3,supplyingoptionstoA t v R c r : B s . i d c i e e o d : a e f n methodisdiscouraged.Usec l e t o . h r insteadwhenyouneedto olcinwee passconditions.

4.4.1.12c l e t o . h r ( ) olcinwee Thec l e t o . h r methodfindsobjectswithinthecollectionbasedontheconditionssuppliedbuttheobjectsareloadedlazilymeaningthatthe olcinwee

Thec l e t o . h r methodfindsobjectswithinthecollectionbasedontheconditionssuppliedbuttheobjectsareloadedlazilymeaningthatthe olcinwee databaseisqueriedonlywhentheobject(s)areaccessed.Italsoaddstheadditionalconditionthattheobjectmustbeinthecollection.

@e_ ebi a e = @a .sebiswee asmle.hr( "rae_t>? cetda" , 2 .asao dy.g)

4.4.1.13c l e t o . x s s ( ) olcineit? Thec l e t o . x s s methodcheckswhetheranobjectmeetingthesuppliedconditionsexistsinthecollection.Itusesthesamesyntaxand olcineit? optionsasA t v R c r : B s . x s s . cieeod:aeeit? 4.4.1.14c l e t o . u l ( t r b t s = { ) olcinbidatiue} Thec l e t o . u l methodreturnsanewobjectoftheassociatedtype.Thisobjectwillbeinstantiatedfromthepassedattributes,andthelink olcinbid throughthejointablewillbecreated,buttheassociatedobjectwillnotyetbesaved.

@ eb a = @a .sebisbid asmle.ul( { : eb _ae a = > "rnmsinhuig Tasisoosn" } )

4.4.1.15c l e t o . r a e a t i u e } olcincet(trbts={) Thec l e t o . r a e o l c i n c e t methodreturnsanewobjectoftheassociatedtype.Thisobjectwillbeinstantiatedfromthepassedattributes,thelink throughthejointablewillbecreated,andtheassociatedobjectwillbesaved(assumingthatitpassesanyvalidations).

@ eb a = @a .sebiscet( asmle.rae { : eb _ae a = > "rnmsinhuig Tasisoosn" } )

4.4.2Optionsforh _ d b a a _e

g_ _a

Inmanysituations,youcanusethedefaultbehaviorforh s a d b l n s t _ a y a _ n _ e o g _ o m n withoutanycustomization.Butyoucanalterthatbehaviorina numberofways.Thissectioncoverstheoptionsthatyoucanpasswhenyoucreateah s a d b l n s t _ a y a _ n _ e o g _ o m n association.Forexample,an associationwithseveraloptionsmightlooklikethis:

cas ls Prs<AtvRcr:Bs atcieeod:ae hsadblnst_ay a_n_eog_omn

hsadblnst_ay a_n_eog_omn : ebi a e , : i = > tu re , :ed a_ = > tu re ed n

Theh s a d b l n s t _ a y a _ n _ e o g _ o m n associationsupportstheseoptions:
:soito_oeg_e ascainfrinky :uoae atsv :ls_ae casnm :odtos cniin :one_q cutrsl :eeesl dlt_q :xed etn :idrsl fne_q :oeg_e frinky :ru gop :nld icue :netsl isr_q :ontbe ji_al :ii lmt :fst ofe :re odr :edny raol :eet slc :nq ui :aiae vldt

4.4.2.1: s o i t o _ o e g _ e ascainfrinky Byconvention,Railsguessesthatthecolumninthejointableusedtoholdtheforeignkeypointingtotheothermodelisthenameofthatmodelwith thesuffix_ d i added.The: s o i t o _ o e g _ e optionletsyousetthenameoftheforeignkeydirectly: ascainfrinky The: o e g _ e and: s o i t o _ o e g _ e optionsareusefulwhensettingupamanytomanyselfjoin.Forexample: frinky ascainfrinky

cas ls Uecieeod:ae sr<AtvRcr:Bs hsadblnst_ay a_n_eog_omn : i d f e , : a _ae c = > "sr Ue" , : eg_e f i = > "hsue_d ti_sri" , : a cai _ eg_e i f i

= > "te_sri" ohrue_d ed n

4.4.2.2: u o a e atsv Ifyousetthe: u o a e a t s v optiontot u ,Railswillsaveanyloadedmembersanddestroymembersthataremarkedfordestructionwheneveryou re savetheparentobject. 4.4.2.3: l s _ a e casnm Ifthenameoftheothermodelcannotbederivedfromtheassociationname,youcanusethe: l s _ a e c a s n m optiontosupplythemodelname.For example,ifaparthasmanyassemblies,buttheactualnameofthemodelcontainingassembliesisG d e ,you dsetthingsupthisway: agt

cas ls Prs<AtvRcr:Bs atcieeod:ae hsadblnst_ay a_n_eog_omn : ebi a e , : a _ae c = > "agt Gde" ed n

4.4.2.4: o d t o s cniin The: o d t o s c n i i n optionletsyouspecifytheconditionsthattheassociatedobjectmustmeet(inthesyntaxusedbyanSQLW E E H R clause).

cas ls Prs<AtvRcr:Bs atcieeod:ae hsadblnst_ay a_n_eog_omn : ebi a e , : d i c i = > "atrSate" fco ='etl' ed n

Youcanalsosetconditionsviaahash:

cas ls Prs<AtvRcr:Bs atcieeod:ae hsadblnst_ay a_n_eog_omn : ebi a e , : d i c i = >{ :a fc = > 'etl' Sate } ed n

ed n

Ifyouuseahashstyle: o d t o s c n i i n option,thenrecordcreationviathisassociationwillbeautomaticallyscopedusingthehash.Inthiscase,using
@ a t . s e b i s c e t or@ a t . s e b i s b i d prsasmle.rae p r s a s m l e . u l willcreateorderswherethef c o y a t r columnhasthevalueSeattle.

4.4.2.5: o n e _ q cutrsl NormallyRailsautomaticallygeneratestheproperSQLtocounttheassociationmembers.Withthe: o n e _ q option,youcanspecifya cutrsl completeSQLstatementtocountthemyourself. Ifyouspecify: i d r s l f n e _ q butnot: o n e _ q ,thenthecounterSQLwillbegeneratedbysubstitutingS L C O N ( ) F O forthe cutrsl EETCUT*RM
SLC.RM E E T . . F O clauseofyour: i d r s l f n e _ q statement.

4.4.2.6: e e e s l dlt_q NormallyRailsautomaticallygeneratestheproperSQLtoremovelinksbetweentheassociatedclasses.Withthe: e e e s l d l t _ q option,youcan specifyacompleteSQLstatementtodeletethemyourself. 4.4.2.7: x e d etn The: x e d e t n optionspecifiesanamedmoduletoextendtheassociationproxy.Associationextensionsarediscussedindetaillaterinthisguide. 4.4.2.8: i d r s l fne_q NormallyRailsautomaticallygeneratestheproperSQLtofetchtheassociationmembers.Withthe: i d r s l f n e _ q option,youcanspecifyacomplete SQLstatementtofetchthemyourself.IffetchingobjectsrequirescomplexmultitableSQL,thismaybenecessary. 4.4.2.9: o e g _ e frinky Byconvention,Railsguessesthatthecolumninthejointableusedtoholdtheforeignkeypointingtothismodelisthenameofthismodelwiththe suffix_ d i added.The: o e g _ e optionletsyousetthenameoftheforeignkeydirectly: frinky

cas ls Uecieeod:ae sr<AtvRcr:Bs hsadblnst_ay a_n_eog_omn : i d f e , : a _ae c = > "sr Ue" , : eg_e f i = > "hsue_d ti_sri" , : a cai _ eg_e i f i = > "te_sri" ohrue_d ed n

4.4.2.10: r u gop The: r u optionsuppliesanattributenametogrouptheresultsetby,usingaG O P B clauseinthefinderSQL. gop RUY

cas ls Prs<AtvRcr:Bs atcieeod:ae hsadblnst_ay a_n_eog_omn : ebi a e

, : g = > "atr" fco ed n

4.4.2.11: n l d icue Youcanusethe: n l d optiontospecifysecondorderassociationsthatshouldbeeagerloadedwhenthisassociationisused. icue 4.4.2.12: n e t s l isr_q NormallyRailsautomaticallygeneratestheproperSQLtocreatelinksbetweentheassociatedclasses.Withthe: n e t s l i s r _ q option,youcan specifyacompleteSQLstatementtoinsertthemyourself. 4.4.2.13: o n t b e ji_al Ifthedefaultnameofthejointable,basedonlexicalordering,isnotwhatyouwant,youcanusethe: o n t b e j i _ a l optiontooverridethedefault. 4.4.2.14: i i lmt The: i i optionletsyourestrictthetotalnumberofobjectsthatwillbefetchedthroughanassociation. lmt

cas ls Prs<AtvRcr:Bs atcieeod:ae hsadblnst_ay a_n_eog_omn : ebi a e , : d e = > "rae_tDS" cetdaEC , :ii = > 5 0 ed n

4.4.2.15: f s t ofe The: f s t o f e optionletsyouspecifythestartingoffsetforfetchingobjectsviaanassociation.Forexample,ifyouset: f s t = 1 o f e > 1 ,itwillskip thefirst11records. 4.4.2.16: r e odr The: r e optiondictatestheorderinwhichassociatedobjectswillbereceived(inthesyntaxusedbyanSQLO D R B clause). odr REY

cas ls Prs<AtvRcr:Bs atcieeod:ae hsadblnst_ay a_n_eog_omn : ebi a e , : d e = > "seb _aeAC asml nmS" ed n

4.4.2.17: e d n y raol Ifyousetthe: e d n y r a o l optiontot u ,thentheassociatedobjectswillbereadonlywhenretrievedviatheassociation. re

Ifyousetthe: e d n y r a o l optiontot u ,thentheassociatedobjectswillbereadonlywhenretrievedviatheassociation. re 4.4.2.18: e e t slc The: e e t s l c optionletsyouoverridetheSQLS L C clausethatisusedtoretrievedataabouttheassociatedobjects.Bydefault,Railsretrievesall EET columns. 4.4.2.19: n q ui Specifythe: n q = r e u i > t u optiontoremoveduplicatesfromthecollection. 4.4.2.20: a i a e vldt Ifyousetthe: a i a e v l d t optiontof l e a s ,thenassociatedobjectswillnotbevalidatedwheneveryousavethisobject.Bydefault,thisist u : re associatedobjectswillbevalidatedwhenthisobjectissaved. 4.4.3WhenareObjectsSaved? Whenyouassignanobjecttoah s a d b l n s t _ a y a _ n _ e o g _ o m n association,thatobjectisautomaticallysaved(inordertoupdatethejointable).Ifyou assignmultipleobjectsinonestatement,thentheyareallsaved. Ifanyofthesesavesfailsduetovalidationerrors,thentheassignmentstatementreturnsf l e a s andtheassignmentitselfiscancelled. Iftheparentobject(theonedeclaringtheh s a d b l n s t _ a y a _ n _ e o g _ o m n association)isunsaved(thatis,n w r c r ? e _ e o d returnst u )thenthechild re objectsarenotsavedwhentheyareadded.Allunsavedmembersoftheassociationwillautomaticallybesavedwhentheparentissaved. Ifyouwanttoassignanobjecttoah s a d b l n s t _ a y a _ n _ e o g _ o m n associationwithoutsavingtheobject,usethec l e t o . u l method. olcinbid

4.5AssociationCallbacks
NormalcallbackshookintothelifecycleofActiveRecordobjects,allowingyoutoworkwiththoseobjectsatvariouspoints.Forexample,youcanuse a: e o e s v callbacktocausesomethingtohappenjustbeforeanobjectissaved. bfr_ae Associationcallbacksaresimilartonormalcallbacks,buttheyaretriggeredbyeventsinthelifecycleofacollection.Therearefouravailable associationcallbacks:
bfr_d eoead atrad fe_d bfr_eoe eoermv atrrmv fe_eoe

Youdefineassociationcallbacksbyaddingoptionstotheassociationdeclaration.Forexample:

cas ls Csoecieeod:ae utmr<AtvRcr:Bs hsmn a_ay : d e , :e ead bf _d = > :hc_ ei_ii ce c d df e cekcei_ii(re) hc_rdtlmtodr .. . ed n ed n

Railspassestheobjectbeingaddedorremovedtothecallback.

Railspassestheobjectbeingaddedorremovedtothecallback. Youcanstackcallbacksonasingleeventbypassingthemasanarray:

cas ls Csoecieeod:ae utmr<AtvRcr:Bs hsmn a_ay : d e , :e ead bf _d = >[ :hc_ ei_ii ce c d , :ac ae h igcag c _ i _h e ] df e cekcei_ii(re) hc_rdtlmtodr .. . ed n df e cluaesipn_hre(re) aclt_hpigcagsodr .. . ed n ed n

Ifab f r _ d callbackthrowsanexception,theobjectdoesnotgetaddedtothecollection.Similarly,ifab f r _ e o e eoead e o e r m v callbackthrowsan exception,theobjectdoesnotgetremovedfromthecollection.

4.6AssociationExtensions
You renotlimitedtothefunctionalitythatRailsautomaticallybuildsintoassociationproxyobjects.Youcanalsoextendtheseobjectsthrough anonymousmodules,addingnewfinders,creators,orothermethods.Forexample:

cas ls Csoecieeod:ae utmr<AtvRcr:Bs hsmn a_ay : d e d o df e fn_yodrpei(re_ubr idb_re_rfxodrnme) fn_yrgo_dodrnme[ idb_eini(re_ubr 0 . . 2 ] ) ed n ed n ed n

ed n

Ifyouhaveanextensionthatshouldbesharedbymanyassociations,youcanuseanamedextensionmodule.Forexample:

mdl oue FnRcnEtnin ideetxeso df e fn_eet idrcn wee hr( "rae_t>? cetda" , 5 .asao dy.g) ed n ed n cas ls Csoecieeod:ae utmr<AtvRcr:Bs hsmn a_ay : d e , : ed e =ideetxeso >FnRcnEtnin ed n cas ls Splecieeod:ae upir<AtvRcr:Bs hsmn a_ay :eiei d e , : ed e =ideetxeso >FnRcnEtnin ed n

Toincludemorethanoneextensionmoduleinasingleassociation,specifyanarrayofmodules:

cas ls Csoecieeod:ae utmr<AtvRcr:Bs hsmn a_ay : d e , : ed e =FnRcnEtninidciexeso] >[ideetxeso,FnAtvEtnin ed n

Extensionscanrefertotheinternalsoftheassociationproxyusingthesethreeaccessors:
poyonr r x _ w e returnstheobjectthattheassociationisapartof. p o y r f e t o returnsthereflectionobjectthatdescribestheassociation. rx_elcin p o y t r e returnstheassociatedobjectforb l n s t orh s o e rx_agt eog_o a _ n ,orthecollectionofassociatedobjectsforh s m n or a_ay hsadblnst_ay a_n_eog_omn.

hsadblnst_ay a_n_eog_omn.

5Changelog
April7,2010:FixeddocumenttovalidateXHTML1.0Strict.JaimeIniesta April19,2009:Added: o c optiontob l n s t associationsbyMikeGunderloy tuh eog_o February1,2009:Added: u o a e a t s v optionMikeGunderloy September28,2008:Correctedh s m n t r u h a _ a y : h o g diagram,addedpolymorphicdiagram,somereorganizationbyMikeGunderloy.First releaseversion. September22,2008:Addeddiagrams,misc.cleanupbyMikeGunderloy(notyetapprovedforpublication) September14,2008:initialversionbyMikeGunderloy(notyetapprovedforpublication)

Feedback
You'reencouragedtohelpimprovethequalityofthisguide. Ifyouseeanytyposorfactualerrorsyouareconfidenttopatch,pleaseclonedocrailsandpushthechangeyourself.ThatbranchofRailshaspublic writeaccess.Commitsarestillreviewed,butthathappensafteryou'vesubmittedyourcontribution.docrailsiscrossmergedwithmasterperiodically. Youmayalsofindincompletecontent,orstuffthatisnotuptodate.Pleasedoaddanymissingdocumentationformaster.ChecktheRubyonRails GuidesGuidelinesforstyleandconventions. Ifforwhateverreasonyouspotsomethingtofixbutcannotpatchityourself,pleaseopenanissue. Andlastbutnotleast,anykindofdiscussionregardingRubyonRailsdocumentationisverywelcomeintherubyonrailsdocsmailinglist. ThisworkislicensedunderaCreativeCommonsAttributionShareAlike3.0License "Rails","RubyonRails",andtheRailslogoaretrademarksofDavidHeinemeierHansson.Allrightsreserved.

Anda mungkin juga menyukai