A Guide To Active Record Associations: Chapters
A Guide To Active Record Associations: Chapters
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
Now,supposewewantedtoaddaneworderforanexistingcustomer.We dneedtodosomethinglikethis:
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
Withthischange,creatinganeworderforaparticularcustomeriseasier:
Deletingacustomerandallofitsordersismucheasier:
@ c e .eto dsry
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
2.1Theb e
g _ Association
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:
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:
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
pyiinptetains hsca.ains=ptet
newjoinmodelsarecreatedfornewlyassociatedobjects,andifsomearegonetheirrowsaredeleted.
Automaticdeletionofjoinmodelsisdirect,nodestroycallbacksaretriggered.
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
@ c e d .aarps prgah
2.5Theh _ e : h a
g Association h
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
2.6The h _ db a a _e Association
g_ _a
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:
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
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:
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
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
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
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
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
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
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
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
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
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
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
Eachinstanceoftheordermodelwillhavethesemethods:
@ 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
e_ae
4.1.2Optionsforb e
g_
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
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
: a _ae c
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
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.
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
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
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
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:
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?
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}
@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
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:
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 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
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.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.
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?
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:
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={)
@ d e = @ c e .res odr
@ c e .res< odr< @ d 1 e
@ c e .resdlt( odr.eee @ d 1 e )
@ 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
@ d _ e c = @ c e .ressz odr.ie
4.3.1.11c l e t o . h r ( ) olcinwee
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.
b e
cas ls Csoecieeod:ae utmr<AtvRcr:Bs hsmn a_ay : d e , :eed d e = > :eeea d _ , :aiae d = > :a e f ed n
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 :ieie _ , :h g h = > : d e , : g = > "resi" odr.d ed n
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
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
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
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.
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>
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
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:
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={)
@a .sebis< asmle< @ eb 1 a
@a .sebisdlt( asmle.eee @ eb 1 a )
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
@ eb _ a c = @a .sebissz asmle.ie
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.
4.4.2Optionsforh _ d b a a _e
g_ _a
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
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
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.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
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
4.6AssociationExtensions
You renotlimitedtothefunctionalitythatRailsautomaticallybuildsintoassociationproxyobjects.Youcanalsoextendtheseobjectsthrough anonymousmodules,addingnewfinders,creators,orothermethods.Forexample:
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:
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.