Tải bản đầy đủ (.pdf) (345 trang)

OReilly ruby on rails up and running 2006 aug 2006 ISBN 0596101325

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (2.46 MB, 345 trang )

RubyonRails:UpandRunning
ByCurtHibbs,BruceA.Tate
...............................................
Publisher:O'Reilly
PubDate:August2006
PrintISBN-10:0-596-10132-5
PrintISBN-13:978-0-59-610132-9
Pages:182

TableofContents|Index

RubyonRailsisthesuper-productivenewwaytodevelopfull-featured
webapplications.WithRubyonRails,powerfulwebapplicationsthat
oncetookweeksormonthstodevelopcannowbeproducedinamatterof
days.Ifitsoundstoogoodtobetrue,itisn't.

Ifyou'relikealotofwebdevelopers,you'veprobablyconsidered
kickingthetiresonRails-theframeworkofchoiceforthenew
generationofWeb2.0developers.RubyonRails:UpandRunningfromO'Reillytakesyou
outforatestdriveandshowsyoujusthowfast
RubyonRailscango.

Thiscompactguideteachesyouthebasicsofinstallingandusingboth
theRubyscriptinglanguageandtheRailsframeworkforthequick
developmentofwebapplications.RubyonRails:Upand
Runningcoversjustabouteverythingyou
need-frommakingasimpledatabase-backedapplicationto
addingelaborateAjaxianfeaturesandallthejuicybitsinbetween.
WhileRailsispraisedforitssimplicityandspeedofdevelopment,
therearestillafewstepstomasterontheway.Moreadvanced
materialhelpsyoumapdatatoanimperfecttable,traversecomplex


relationships,andbuildcustomfinders.AsectiononworkingwithAjax
andRESTshowsyouhowtoexploittheRailsserviceframeworkstosend
emails,implementwebservices,andcreatedynamicuser-centricweb
pages.Thebookalsoexplainstheessentialsofloggingtofind
performanceproblemsanddelvesintootherperformanceoptimizing
techniques.


Asnewwebdevelopmentframeworksgo,RubyonRailsisthetalkofthe
town.AndRubyonRails:UpandRunningcanmake
sureyou'reinonthediscussion.


RubyonRails:UpandRunning
ByCurtHibbs,BruceA.Tate
...............................................
Publisher:O'Reilly
PubDate:August2006
PrintISBN-10:0-596-10132-5
PrintISBN-13:978-0-59-610132-9
Pages:182

TableofContents|Index
















































Copyright
Preface
Chapter1.ZerotoSixty:IntroducingRails
Section1.1.RailsStrengths
Section1.2.PuttingRailsintoAction
Section1.3.Organization
Section1.4.TheWebServer
Section1.5.CreatingaController
Section1.6.BuildingaView
Section1.7.TyingtheControllertotheView
Section1.8.UndertheHood
Section1.9.What'sNext?
Chapter2.ActiveRecordBasics
Section2.1.ActiveRecordBasics
Section2.2.IntroducingPhotoShare
Section2.3.SchemaMigrations
Section2.4.BasicActiveRecordClasses
Section2.5.Attributes
Section2.6.ComplexClasses
Section2.7.Behavior
Section2.8.MovingForward

Chapter3.ActiveRecordRelationships
Section3.1.belongs_to
Section3.2.has_many














































































Section3.3.has_one
Section3.4.WhatYouHaven'tSeen
Section3.5.LookingAhead
Chapter4.Scaffolding
Section4.1.UsingtheScaffoldMethod
Section4.2.ReplacingScaffolding
Section4.3.GeneratingScaffoldingCode
Section4.4.MovingForward
Chapter5.ExtendingViews
Section5.1.TheBigPicture
Section5.2.SeeingRealPhotos

Section5.3.ViewTemplates
Section5.4.SettingtheDefaultRoot
Section5.5.Stylesheets
Section5.6.HierarchicalCategories
Section5.7.StylingtheSlideshows
Chapter6.Ajax
Section6.1.HowRailsImplementsAjax
Section6.2.PlayingaSlideshow
Section6.3.UsingDrag-and-DroptoReorderSlides
Section6.4.DragandDropEverything(AlmostEverything)
Section6.5.FilteringbyCategory
Chapter7.Testing
Section7.1.Background
Section7.2.Ruby'sTest::Unit
Section7.3.TestinginRails
Section7.4.WrappingUp
AppendixA.InstallingRails
Section1.1.Windows
Section2.1.OSX
Section3.1.Linux
AppendixB.QuickReference
Section5.1.General
Section5.2.Testing
Section5.3.RJS(RubyJavaScript)
Section5.4.ActiveRecord
Section5.5.Controllers
Section5.6.Views
Section5.7.Ajax




Section5.8.ConfiguringYourApplication

AbouttheAuthors

Colophon

Index


RubyonRails:UpandRunning
byBruceA.TateandCurtHibbs
Copyright©2006O'ReillyMedia,Inc.Allrightsreserved.
PrintedintheUnitedStatesofAmerica.
PublishedbyO'ReillyMedia,Inc.,1005GravensteinHighway
North,Sebastopol,CA95472.
O'Reillybooksmaybepurchasedforeducational,business,or
salespromotionaluse.Onlineeditionsarealsoavailablefor
mosttitles(safari.oreilly.com).Formoreinformation,contact
ourcorporate/institutionalsalesdepartment:(800)998-9938or

Editor:

MikeLoukides

ProductionEditor:

AdamWitwer

Copyeditor:


NancyKotary

Proofreader:

MaryAnneWeeksMayo

Indexer:

JohnBicklehaupt

CoverDesigner:

KarenMontgomery

InteriorDesigner:

DavidFutato

Illustrators:

RobertRomanoandJessamynRead

PrintingHistory:



August2006:

FirstEdition.



NutshellHandbook,theNutshellHandbooklogo,andthe
O'ReillylogoareregisteredtrademarksofO'ReillyMedia,Inc.
RubyonRails:UpandRunning,theimageofanibex,and
relatedtradedressaretrademarksofO'ReillyMedia,Inc.
ThisworkislicensedundertheCreativeCommonsLicense
Attribution2.0.ToviewacopyofthisLicense,visit
orsendaletterto
CreativeCommons,543HowardStreet,5thFloor,San
Francisco,California94105-3013,USA.
Manyofthedesignationsusedbymanufacturersandsellersto
distinguishtheirproductsareclaimedastrademarks.Where
thosedesignationsappearinthisbook,andO'ReillyMedia,Inc.
wasawareofatrademarkclaim,thedesignationshavebeen
printedincapsorinitialcaps.
Whileeveryprecautionhasbeentakeninthepreparationofthis
book,thepublisherandauthorsassumenoresponsibilityfor
errorsoromissions,orfordamagesresultingfromtheuseof
theinformationcontainedherein.
ISBN-13:978-0-596-10132-9|ISBN-10:0-596-10132-5
[M]


Preface
TheRubyonRailsphenomenonissweepingthroughour
industrywithrecklessdisregardforestablishedprogramming
languages,longstandingconventions,orcommercialsupport.
YoucangetawholelotofinformationonRubyonRailsfrom
articlesontheWeb,excellentbooks,andevenformal

coursework.However,there'ssomethingmissing.Howdoesan
establishedprogrammer,armedwithnothingmorethanalittle
Rubyknowledge,gojustbeyondthebasics,andbeproductive
inRails?
WithRubyonRails:UpandRunning,wearenotgoingto
reiteratethereferencemanualorreplaceGoogle.Instead,we'll
strivetogiveyouthebigpictureofhowRailsapplicationshold
togetherandtellyouwheretogofortheinformationthatwe
don'tcoverinthechapters.YouwillseehowRailsdynamically
addsfeaturestoalldatabasemodels,calledActiveRecord
objects.Byunderstandingthebigpicture,you'llbeableto
makebetteruseofthebestreferencemanualstofillinthe
details.
Wewon'ttrytomakeyoudigestawholelotofwords.Instead,
we'llgiveyouthetheoryinthecontextofanend-to-end
application.We'llwalkyouthroughthecreationofasimple
projectonethatisalittlemoredemandingthanablogor
shoppingcart,butwithasimpleenoughstructurethataRails
beginnerwillbeabletoquicklyunderstandwhat'sgoingon.
We'renotgoingtotrytocovereachnewfeature.Instead,we'll
showyoutheonesweseeasthebackbone,formingthemost
importantelementstounderstand.Wewillalsocover
migrationsandAjaxinsomedetail,becauseyouwon'tfindtoo
muchinformationonthosetwoframeworksyet.
Inshort,we'renottryingtobuildacomprehensiveRailslibrary.


We'regoingtogiveyouthefoundationyouneedtogetupand
running.


WhoShouldReadThisBook?
RubyonRails:UpandRunningisforexperienceddevelopers
whoarenewtoRailsandpossiblytoRuby.Tousethisbook,
youdon'thavetobeastrongRubyprogrammer.Wedoexpect
youtobeaprogrammer,though.Youshouldknowenough
aboutyourchosenplatformtobeabletowriteprograms,install
software,runscriptsusingthesystemconsole,editfiles,usea
database,andunderstandhowbasicwebapplicationswork.

ConventionsUsedinThisBook
Thefollowingtypographicconventionsareusedinthisbook:

Plaintext
Indicatesmenutitles,menuoptions,menubuttons,and
keyboardaccelerators(suchasAltandCtrl).

Italic
Indicatesnewterms,URLs,emailaddresses,filenames,file
extensions,pathnames,directories,andUnixutilities.

Constantwidth
Indicatescommands,thecontentsoffiles,andtheoutput
fromcommands.


Constantwidthbold
Showscommandsorothertextthatshouldbetyped
literallybytheuser.

Constantwidthitalic


Showstextthatshouldbereplacedwithuser-supplied
values.

Thisiconsignifiesatip,suggestion,orgeneralnote.

Thisiconindicatesawarningorcaution.

UsingCodeExamples
Thisbookisheretohelpyougetyourjobdone.Ingeneral,you
mayusethecodeinthisbookinyourprogramsand
documentation.Youdonotneedtocontactusforpermission
unlessyou'rereproducingasignificantportionofthecode.For
example,writingaprogramthatusesseveralchunksofcode
fromthisbookdoesnotrequirepermission.Sellingor
distributingaCD-ROMofexamplesfromO'Reillybooksdoes
requirepermission.Answeringaquestionbycitingthisbook
andquotingexamplecodedoesnotrequirepermission.


Incorporatingasignificantamountofexamplecodefromthis
bookintoyourproduct'sdocumentationdoesrequire
permission.
YoucangetsamplecodeatthemainpageforRubyonRails:
UpandRunning:You
willfindaZIPfilethatcontainsthesampleprojectasitexists
aftereachchapter,witheachinstanceofthesampleapplication
numberedbychapter.Ifyouwanttoskipachapter,just
downloadtherightZIPfile.
Weappreciate,butdonotrequire,attribution.Anattribution

usuallyincludesthetitle,author,publisher,andISBN.For
example:"RubyonRails:UpandRunningbyBruceA.Tateand
CurtHibbs.Copyright2006O'ReillyMedia,Inc.,978-0-59610132-9."
Ifyoufeelthatyouruseofcodeexamplesfallsoutsidefairuse
orthepermissiongivenhere,feelfreetocontactusat


Platforms
RubyonRailsiscross-platform,butUnixandWindowsshells
behavedifferently.Forconsistency,weuseWindowsthroughout
thebook.YoucaneasilyruntheexamplesontheUnixorMac
OSXoperatingsystemsaswell.You'llseeacoupleofminor
differences:
OnWindows,youcanspecifypathswitheithertheforward
slash(/)orbackslash(\)character.We'lltrytobe
consistentandusetheforwardslashtospecifyallpaths.
OnWindows,torunthevariousRubyscriptsthatmakeup
Rails,youneedtoexplicitlytyperuby.OnUnix
environments,youdon't.Ifyou'rerunningUnix,andyou


areinstructedtotypethecommandrubyscript/server,feel
freetoomittheruby.
OnWindows,torunaprocessinaseparateshell,precede
thecommandwithstart.OnUnixandMacOSX,appendan
ampersand(&)charactertorunthecommandinthe
background.

Safari®Enabled
WhenyouseeaSafari®Enabledicononthecoverof

yourfavoritetechnologybook,thatmeansthebookisavailable
onlinethroughtheO'ReillyNetworkSafariBookshelf.
Safarioffersasolutionthat'sbetterthane-books.It'savirtual
librarythatletsyoueasilysearchthousandsoftoptechbooks,
cutandpastecodesamples,downloadchapters,andfindquick
answerswhenyouneedthemostaccurate,currentinformation.
Tryitforfreeat.

HowtoContactUs
Wehavetestedandverifiedtheinformationinthisbookandin
thesourcecodetothebestofourability,butgiventheamount
oftextandtherapidevolutionoftechnology,youmayfindthat
featureshavechangedorthatwehavemademistakes.Ifso,
pleasenotifyusbywritingto:
O'ReillyMedia,Inc.
1005GravensteinHighwayNorth
Sebastopol,CA95472
800-998-9938(intheUnitedStatesorCanada)


707-829-0515(internationalorlocal)
707-829-0104(fax)
Youcanalsosendmessageselectronically.Tobeputonthe
mailinglistorrequestacatalog,sendemailto:

Toasktechnicalquestionsorcommentonthebook,sendemail
to:

Asmentionedintheearliersection,wehaveawebsiteforthis
bookwhereyoucanfindcode,errata(previouslyreported

errorsandcorrectionsavailableforpublicview),andotherbook
information.Youcanaccessthiswebsiteat:
/>Formoreinformationaboutthisbookandothers,seethe
O'Reillywebsite:


Acknowledgments
Writingabookisademandingexercise,takingpassion,
commitment,andpersistence.Theauthorsonthecovergetall
oftheglory(andpossiblytheblame).Manypeoplecontribute
toabook.We'dliketomentionthepeoplewhomadewriting
thisbooksuchafulfillingexperience.
Collectively,CurtandBrucewouldliketothanktheoutstanding


teamofreviewerswhoprovidedsomanygreatcomments,
includingDavidMabelle,MauroCicio,BrookeHedrick,Faisal
Jawdat,ShaneClaussen,LeodeBlaauw,AnneBowman,Seth
Havermann,DaveHastings,andRandyHanford.We'dalsolike
tothankDavidGearyforfleshingoutsomeoftheearlyideasin
PhotoShare.
RubyonRails:UpandRunningwouldbenothingwithoutthe
excellentcontributionsofthecoreRubyonRailsteam.We
wouldliketothankDavidHeinemeierHansson(thecreatorof
Rails),FlorianWeber,JamisBuck,JeremyKemper,LeonBreedt,
MarcelMolina,Jr.,MichaelKoziarski,NicholasSeckar,Sam
Stephenson,ScottBarron,ThomasFuchs,andTobiasLuetke.
Rubyisafantasticlanguage,andwewouldliketothankthe
manywhomadeitso.WethrowoutspecificthankstoYukihiro
Matsumoto(a.k.a."Matz"),thecreatorofRuby,andtoDave

ThomasandAndyHunt,withoutwhomRubymighthave
remainedvirtuallyunknownoutsideofJapan.
BrucewouldliketospecificallythankCurt,forsteppingintothis
projectafteritseemedthatitwasdead.Also,thankstothose
atAutoGaswhoweresoinstrumentalintryingthistechnology
withinthecontextofarealproductionapplicationespeciallythe
coredevelopmentteam,includingMathewVarghese,Karl
Hoenshel,CheriByerley,ChrisGindorf,andColbyBlaisdell.
Theircollectiveexperienceshapedthisbookmorethanyouwill
everknow.ThankstomyDutchfriendLeo,again,forbeing
suchasupportiveinfluenceonthisbook,thoughyou'remostly
aJavadeveloper.Youhavehadmoreinfluenceonmethanyou
mightexpect.Morethananyoneelse,Iwouldliketothankmy
family.KaylaandJulia,youarethesparksinmysoulthatkeep
thecreativefiresburning.Maggie,youaremyinspiration,andI
loveyoumorethanIcaneversay.
Curtwouldliketothankhiswife,Wasana,forlettinghim
disappearbehindhiscomputerscreenlateintothenight(and
sometimesintothefollowingday)withoutcomplaint.Iwould
alsoliketothankmyfriendsatO'Reilly,forgivingmeaforum


tospreadthewordabouttheincredibleproductivityadvantages
ofRubyonRails.Specifically,I'dliketothankchromaticfor
publishingmyONLamp.comarticles,andMikeLoukidesfornot
givingupwhenIkepttellinghimIdidn'twanttowriteabook.


Chapter1.ZerotoSixty:Introducing
Rails

Railsmayjustbethemostimportantopensourceprojecttobe
introducedinthepast10years.It'spromotedasoneofthe
mostproductivewebdevelopmentframeworksofalltimeandis
basedontheincreasinglyimportantRubyprogramming
language.Whathashappenedsofar?
ByDecember2006,you'relikelytoseemorepublished
booksonRailsthananyofJava'ssingleflagship
frameworks,includingJSF,Spring,orHibernate.
TheRailsframeworkhasbeendownloadedatleast500,000
timesinonlyitssecondyear,asofMay2006.These
statisticscomparefavorablywiththemostpopularopen
sourceframeworksinanylanguage.[*]
[*]Thenumber500,000isactuallyaconservativeestimate.Downloadstatisticsforapopulardelivery
vehicle,calledgems,makeiteasytotrackthenumberofRailsdistributionsbygems,butmanyother
distributionsexist,suchastheLocomotivedistributiononMacOSX.Therealdownloadstatisticscould
easilybetwicethisnumber.

TheRailscommunitymailinglistsgethundredsofnotesa
day,comparedtodozensonthemostpopularweb
developmentframeworksinotherlanguages.
TheRailsframeworkhascausedanexplosionintheuseof
theRubyprogramminglanguage,whichhasbeenrelatively
obscureuntilrecently.
TheRailsbuzzgeneratesincreasinglyhotdebateson
portalsthatfocusonotherprogramminglanguages.The
JavacommunityinparticularhasfiercelydebatedtheRails


platform.
Youdon'thavetogofartofindgreatoverviewsofRails.You

canwatchseveraleducationalvideosthatshowRailsinaction,
narratedbythefounderDavidHeinemeierHansson.Youcan
watchhimbuildsimpleworkingapplications,completewitha
backingdatabaseandvalidation,inlessthan10minutes.But
unlikethemanyquick-and-dirtyenvironmentsyou'veseen,
Railsletsyoukeepthequickandleavethedirtybehind.Itlets
youbuildcleanapplicationsbasedonthemodel-view-controller
philosophy.Railsisaspecialframework.
Sure,Railshasitslimitations.Rubyhaspoorsupportforobjectrelationalmapping(ORM)forlegacyschemas;theRails
approachislesspowerfulthanJava'sapproach,forexample.[*]
Rubydoesnotyethaveflagshipintegrateddevelopment
environments.Everyframeworkhaslimitations,andRailsisno
different.Butforawiderangeofapplications,thestrengthsof
Railsfaroutpaceitsweaknesses.
[*]Forexample,Hibernatesupportsthreekindsofinheritancemapping,butRailssupportsonlysingle-table
inheritance.Hibernatesupportscompositekeys,butRailsismuchmorelimited.


1.1.RailsStrengths
Asyougothroughthisbook,you'lllearnhowRailscanthrive
withoutalloftheextensivelibrariesrequiredbyother
languages.Ruby'sflexibilityletsyouextendyourapplicationsin
waysthatmighthavebeenpreviouslyunavailabletoyou.You'll
beabletouseaRailsfeaturecalledscaffoldingtoputdatabasebackeduserinterfacesinfrontofyourcustomersquickly.Then,
asyouimproveyourcode,thescaffoldingmeltsaway.You'llbe
abletobuilddatabase-backedmodelobjectswithjustacouple
oflinesofcode,andRailswillfillinthetediousdetails.
Themostcommonprogrammingproblemintoday'stypical
developmentprojectinvolvesbuildingaweb-baseduser
interfacetomanagearelationaldatabase.Forthatclassof

problems,Railsismuchmoreproductivethananyotherweb
developmentframeworkeitherofushaseverused.The
strengthsaren'tlimitedtoanysinglegroundbreakinginvention;
rather,Railsispackedwithfeaturesthatmakeyoumore
productive,withmanyofthefollowingfeaturesbuildingonone
other:

Metaprogramming
Metaprogrammingtechniquesuseprogramstowrite
programs.Otherframeworksuseextensivecode
generation,whichgivesusersaone-timeproductivityboost
butlittleelse,andcustomizationscriptslettheuseradd
customizationcodeinonlyasmallnumberofcarefully
selectedpoints.Metaprogrammingreplacesthesetwo
primitivetechniquesandeliminatestheirdisadvantages.
Rubyisoneofthebestlanguagesformetaprogramming,
andRailsusesthiscapabilitywell.[ ]


[ ]Railsalsousescodegenerationbutreliesmuchmoreonmetaprogrammingfortheheavy
lifting.

ActiveRecord
RailsintroducestheActiveRecordframework,whichsaves
objectstothedatabase.Basedonadesignpattern
catalogedbyMartinFowler,theRailsversionofActive
Recorddiscoversthecolumnsinadatabaseschemaand
automaticallyattachesthemtoyourdomainobjectsusing
metaprogramming.Thisapproachtowrappingdatabase
tablesissimple,elegant,andpowerful.


Conventionoverconfiguration
Mostwebdevelopmentframeworksfor.NETorJavaforce
youtowritepagesofconfigurationcode.Ifyoufollow
suggestednamingconventions,Railsdoesn'tneedmuch
configuration.Infact,youcanoftencutyourtotal
configurationcodebyafactoroffiveormoreoversimilar
Javaframeworksjustbyfollowingcommonconventions.

Scaffolding
Youoftencreatetemporarycodeintheearlystagesof
developmenttohelpgetanapplicationupquicklyandsee
howmajorcomponentsworktogether.Railsautomatically
createsmuchofthescaffoldingyou'llneed.

Built-intesting


Railscreatessimpleautomatedtestsyoucanthenextend.
Railsalsoprovidessupportingcodecalledharnessesand
fixturesthatmaketestcaseseasiertowriteandrun.Ruby
canthenexecuteallyourautomatedtestswiththerake
utility.

Threeenvironments:development,testing,andproduction
Railsgivesyouthreedefaultenvironments:development,
testing,andproduction.Eachbehavesslightlydifferently,
makingyourentiresoftwaredevelopmentcycleeasier.For
example,RailscreatesafreshcopyoftheTestdatabasefor
eachtestrun.

There'smuchmore,too,includingAjaxforrichuserinterfaces,
partialviewsandhelpersforreusingviewcode,built-incaching,
amailingframework,andwebservices.Wecan'tgettoallof
Rails'featuresinthisbook;however,wewillletyouknow
wheretogetmoreinformation.Butthebestwaytoappreciate
Railsistoseeitinaction,solet'sgettoit.




1.2.PuttingRailsintoAction
YoucouldmanuallyinstallallofthecomponentsforRails,but
Rubyhassomethingcalledgems.Thegeminstalleraccessesa
website,RubyForge,anddownloadsanapplicationunit,called
agem,andallitsdependencies.YoucaninstallRailsthrough
gems,requestingalldependencies,withthiscommand:[*]
[*]Ifyouwanttocodealongwithus,makesureyou'veinstalledRubyandgems.AppendixAcontainsdetailed
installationinstructions.

geminstallrails--include-dependencies

That'sitRailsisinstalled.There'sonecaveat:youalsoneedto
installthedatabasesupportforyourgivendatabase.Ifyou've
alreadyinstalledMySQL,you'redone.Ifnot,goto
formoredetailsonRailsinstallation.
Next,here'showtocreateaRailsproject:


MVCandModel2
Inthemid-1970s,theMVC(model-view-controller)strategyevolvedinthe

Smalltalkcommunitytoreducecouplingbetweenbusinesslogicandpresentation
logic.WithMVC,youputyourbusinesslogicintoseparatedomainobjectsand
isolateyourpresentationlogicinaview,whichpresentsdatafromdomain
objects.Thecontrollermanagesnavigationbetweenviews,processesuserinput,
andmarshalsthecorrectdomainobjectsbetweenthemodelandview.Good
programmershaveusedMVCeversince,implementingMVCapplicationsusing
frameworkswritteninmanydifferentlanguages,includingRuby.
WebdevelopersuseasubtlydifferentvariantofMVCcalledModel2.Model2uses
thesameprinciplesofMVCbuttailorsthemforstatelesswebapplications.In
Model2applications,abrowsercallsacontrollerviawebstandards.The
controllerinteractswiththemodeltogetdataandvalidateuserinput,andthen
makesdomainobjectsavailabletotheviewfordisplay.Next,thecontroller
invokesthecorrectviewgenerator,basedonvalidationresultsorretrieveddata.
Theviewlayergeneratesawebpage,usingdataprovidedbythecontroller.The
frameworkthenreturnsthewebpagetotheuser.IntheRailscommunity,when
someonesaysMVC,they'rereferringtotheModel2variant.
Model2hasbeenusedinmanysuccessfulprojectsspreadacrossmany
programminglanguages.IntheJavacommunity,Strutsisthemostcommon
Model2framework.InPython,theflagshipwebdevelopmentframeworkcalled
ZopeusesModel2.Youcanreadmoreaboutthemodel-view-controllerstrategy
at />
>railschapter-1
create
createapp/controllers
createapp/helpers
createapp/models
createapp/views/layouts
createconfig/environments
createcomponents
createdb

createdoc
createlib


...
createtest/mocks/development
createtest/mocks/test
createtest/unit
createvendor
...
createapp/controllers/application.rb
createapp/helpers/application_helper.rb
createtest/test_helper.rb
createconfig/database.yml
...

Wetruncatedthelist,butyougetthepicture.


1.3.Organization
Thedirectoriescreatedduringinstallationprovideaplacefor
yourcode,scriptstohelpyoumanageandbuildyour
application,andmanyothergoodies.Later,we'llexaminethe
mostinterestingdirectoriesingreaterdetail.Fornow,let'stake
aquickpassthroughthedirectorytreeintheprojectwe
created:

app
Thisapplicationorganizesyourapplicationcomponents.It's
gotsubdirectoriesthatholdtheview(viewsandhelpers),

controller(controllers),andthebackendbusinesslogic
(models).

components
Thisdirectoryholdscomponentstinyself-contained
applicationsthatbundlemodel,view,andcontroller.

config
Thisdirectorycontainsthesmallamountofconfiguration
codethatyourapplicationwillneed,includingyour
databaseconfiguration(indatabase.yml),yourRails
environmentstructure(environment.rb),androutingof
incomingwebrequests(routes.rb).Youcanalsotailorthe
behaviorofthethreeRailsenvironmentsfortest,
development,anddeploymentwithfilesfoundinthe
environmentsdirectory.


db
Usually,yourRailsapplicationwillhavemodelobjectsthat
accessrelationaldatabasetables.Youcanmanagethe
relationaldatabasewithscriptsyoucreateandplaceinthis
directory.

doc
Rubyhasaframework,calledRubyDoc,thatcan
automaticallygeneratedocumentationforcodeyoucreate.
YoucanassistRubyDocwithcommentsinyourcode.This
directoryholdsalltheRubyDoc-generatedRailsand
applicationdocumentation.


lib
You'llputlibrarieshere,unlesstheyexplicitlybelong
elsewhere(suchasvendorlibraries).

log
Errorlogsgohere.Railscreatesscriptsthathelpyou
managevariouserrorlogs.You'llfindseparatelogsforthe
server(server.log)andeachRailsenvironment
(development.log,test.log,andproduction.log).

public


×