Tải bản đầy đủ (.pdf) (1,579 trang)

ruby on rails tutorial learn web development with rails (3rd ed ) hartl 2015 05 11

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 (49.15 MB, 1,579 trang )


AboutThiseBook
ePUBisanopen,industry-standardformatforeBooks.However,supportofePUBanditsmany
featuresvariesacrossreadingdevicesandapplications.Useyourdeviceorappsettingstocustomize
thepresentationtoyourliking.Settingsthatyoucancustomizeoftenincludefont,fontsize,singleor
doublecolumn,landscapeorportraitmode,andfiguresthatyoucanclickortaptoenlarge.For
additionalinformationaboutthesettingsandfeaturesonyourreadingdeviceorapp,visitthedevice
manufacturer ’sWebsite.
Manytitlesincludeprogrammingcodeorconfigurationexamples.Tooptimizethepresentationof
theseelements,viewtheeBookinsingle-column,landscapemodeandadjustthefontsizetothe
smallestsetting.Inadditiontopresentingcodeandconfigurationsinthereflowabletextformat,we
haveincludedimagesofthecodethatmimicthepresentationfoundintheprintbook;therefore,
wherethereflowableformatmaycompromisethepresentationofthecodelisting,youwillseea
“Clickheretoviewcodeimage”link.Clickthelinktoviewtheprint-fidelitycodeimage.Toreturnto
thepreviouspageviewed,clicktheBackbuttononyourdeviceorapp.


RUBYON RAILS™TUTORIAL
LearnWebDevelopmentwithRails
ThirdEdition

MichaelHartl

NewYork•Boston•Indianapolis•SanFrancisco
Toronto•Montreal•London•Munich•Paris•Madrid
Capetown•Sydney•Tokyo•Singapore•MexicoCity


Manyofthedesignationsusedbymanufacturersandsellerstodistinguishtheirproductsareclaimed
astrademarks.Wherethosedesignationsappearinthisbook,andthepublisherwasawareofa
trademarkclaim,thedesignationshavebeenprintedwithinitialcapitallettersorinallcapitals.


Theauthorandpublisherhavetakencareinthepreparationofthisbook,butmakenoexpressedor
impliedwarrantyofanykindandassumenoresponsibilityforerrorsoromissions.Noliabilityis
assumedforincidentalorconsequentialdamagesinconnectionwithorarisingoutoftheuseofthe
informationorprogramscontainedherein.
Forinformationaboutbuyingthistitleinbulkquantities,orforspecialsalesopportunities(which
mayincludeelectronicversions;customcoverdesigns;andcontentparticulartoyourbusiness,
traininggoals,marketingfocus,orbrandinginterests),pleasecontactourcorporatesalesdepartment
ator(800)382–3419.
Forgovernmentsalesinquiries,pleasecontact
ForquestionsaboutsalesoutsidetheUnitedStates,pleasecontact
VisitusontheWeb:informit.com/aw
LibraryofCongressCataloging-in-PublicationData
Hartl,Michael,author.
[Rubyonrails3tutorial]
Rubyonrailstutorial:learnwebdevelopmentwithrails/MichaelHartl.—Thirdedition.
pagescm
Includesindex.
ISBN978-0-13-407770-3(pbk.:alk.paper)—ISBN0-13-407770-9(pbk.:alk.paper)
1.Rubyonrails(Electronicresource)2.Websitedevelopment.
3.Ruby(Computerprogramlanguage)I.Title.
TK5105.8885.R83H372015
006.7—dc23
2014049130
Copyright©2015MichaelHartl
Allrightsreserved.PrintedintheUnitedStatesofAmerica.Thispublicationisprotectedby
copyright,andpermissionmustbeobtainedfromthepublisherpriortoanyprohibitedreproduction,
storageinaretrievalsystem,ortransmissioninanyformorbyanymeans,electronic,mechanical,
photocopying,recording,orlikewise.Toobtainpermissiontousematerialfromthiswork,please
submitawrittenrequesttoPearsonEducation,Inc.,PermissionsDepartment,200OldTappanRoad,
OldTappan,NewJersey07675,oryoumayfaxyourrequestto(201)236-3290.

ThesourcecodeinRubyonRails™Tutorial,ThirdEdition,isreleasedundertheMITLicense.
ISBN13:978-0-13-407770-3
ISBN10:0-13-407770-9
TextprintedintheUnitedStatesonrecycledpaperatEdwardsBrothersMalloyinAnnArbor,
Michigan.
Firstprinting,April2015
Editor-in-Chief
MarkL.Taub


AcquisitionsEditor
DebraWilliamsCauley
ManagingEditor
JohnFuller
Full-ServiceProductionManager
JulieB.Nahil
CopyEditor
JillE.Hobbs
Indexer
RichardEvans
Proofreader
AndreaFox
Reviewer
WillSommers
AssistantEditor
KimBoedigheimer
CoverDesigner
ChutiPrasertsith
Compositor
LaurelTech



PraiseforMichaelHartl’sBooksandVideosonRubyonRails
“Myformercompany(CDBaby)wasoneofthefirsttoloudlyswitchtoRubyonRails,and
thenevenmoreloudlyswitchbacktoPHP(Googlemetoreadaboutthedrama).Thisbook
byMichaelHartlcamesohighlyrecommendedthatIhadtotryit,andtheRubyonRails™
TutorialiswhatIusedtoswitchbacktoRailsagain.”
—FromtheForewordbyDerekSivers(sivers.org)
Formerly:founderofCDBaby
Currently:founderofThoughtsLtd.
“MichaelHartl’sRailsTutorialbookisthe#1(andonly,inmyopinion)placetostartwhenit
comestobooksaboutlearningRails....It’sanamazingpieceofworkand,unusually,walks
youthroughbuildingaRailsappfromstarttofinishwithtesting.Ifyouwanttoreadjustone
bookandfeellikeaRailsmasterbytheendofit,picktheRubyonRails™Tutorial.”
—PeterCooper,editor,RubyInside
“Fortheself-motivatedreaderwhorespondswelltothe‘learnbydoing’methodandis
preparedtoputintheeffort,thenthiscomeshighlyrecommended.”
—IanElliot,reviewer,IProgrammer
“RubyonRails™Tutorialisalotofworkbutifyou’recarefulandpatient,you’lllearnalot.”
—JasonShen,techentrepreneur,bloggeratTheArtofAss-Kicking
“MichaelHartl’sRubyonRails™TutorialseamlesslytaughtmeaboutnotonlyRubyon
Rails,butalsotheunderlyingRubylanguage,HTML,CSS,abitofJavaScript,andevensome
SQL—butmostimportantlyitshowedmehowtobuildawebapplication(Twitter)inashort
amountoftime.”
—MattanGriffel,co-founder&CEOofOneMonth
“AlthoughI’maPython/Djangodeveloperbytrade,Ican’tstressenoughhowmuchthis
bookhashelpedme.Asanundergraduate,completelydetachedfromindustry,thisbook
showedmehowtouseversioncontrol,howtowritetests,and,mostimportantly—despitethe
steeplearningcurveforsettingupandgettingstuffrunning—howtheend-resultof
perseveranceisextremelygratifying.Itmademefallinlovewithtechnologyalloveragain.

ThisisthebookIdirectallmyfriendstowhowanttostartlearningprogramming/building
stuff.ThankyouMichael!”
—PrakharSrivastav,softwareengineer,Xcite.com,Kuwait
“Itdoesn’tmatterwhatyouthinkyouwillbedevelopingwithinthefutureorwhatthe
frameworkdujouris;ifyouwanttolearnhowtobuildsomething,thereisnobetterplaceto
startthanwiththistutorial.Andforallthe‘non-technical’peopleouttherewhowanttosee
theirideascometolife,whoareconsideringhiringcontractors,payingforaclass,or
‘founderdating’inthesearchforatechnicalco-founder:stop.Takeastepback.Forgetabout
yourideaforashortwhileandimmerseyourselfinthistutorialtolearnwhatittakestoput
somethingtogether.Youandyoursoftware-relatedprojectswillbebetterforit.”


—VincentC.,entrepreneuranddeveloper
“Ithastobethebest-writtenbookofitstypeI’veeverseen,andIcan’trecommendit
enough.”
—DanielHollands,administratorofBirmingham.IO
“ForthosewantingtolearnRubyonRails,Hartl’sRubyonRails™Tutorialis(inmy
opinion)thebestwaytodoit.”
—DavidYoung,softwaredeveloperandauthoratdeepinthecode.com
“Thisisagreattutorialforalotofreasons,becauseasidefromjustteachingRails,Hartlis
alsoteachinggooddevelopmentpractices.”
—MichaelDenomy,full-stackwebdeveloper
“Withoutadoubt,thebestwayIlearnedRubyonRailswasbybuildinganactualworking
app.IusedMichaelHartl’sRubyonRails™Tutorial,whichshowedmehowtogetavery
basicTwitter-likeappupandrunningfromscratch.Icannotrecommendthistutorialenough;
gettingsomethingupandgoingfastwaskey;itbeatsmemorizationbyamile.”
—JamesFend,serialentrepreneur,JamesFend.com
“Thebookgivesyouthetheoryandpractice,whilethevideosfocusonshowingyouin
personhowit’sdone.Highlyrecommendedcombo.”
—AntonioCangiano,softwareengineer,IBM

“TheauthorisclearlyanexpertattheRubylanguageandtheRailsframework,butmorethan
that,heisaworkingsoftwareengineerwhointroducesbestpracticesthroughoutthetext.”
—GregCharles,seniorsoftwaredeveloper,FairwayTechnologies
“Overall,[Hartl’s]videotutorialsshouldbeagreatresourceforanyonenewtoRails.”
—MichaelMorin,ruby.about.com
“Hands-down,IwouldrecommendthisbooktoanyonewantingtogetintoRubyonRails
development.”
—MichaelCrump,MicrosoftMVP



Contents
ForewordtotheFirstEditionbyDerekSivers
ForewordtotheThirdEditionbyObieFernandez
Acknowledgments
AbouttheAuthor
Chapter1FromZerotoDeploy
1.1Introduction
1.1.1Prerequisites
1.1.2ConventionsinThisBook
1.2UpandRunning
1.2.1DevelopmentEnvironment
1.2.2InstallingRails
1.3TheFirstApplication
1.3.1Bundler
1.3.2railsserver
1.3.3Model–View–Controller
1.3.4Hello,World!
1.4VersionControlwithGit
1.4.1InstallationandSetup

1.4.2WhatAretheBenefitsofUsingGit?
1.4.3Bitbucket
1.4.4Branch,Edit,Commit,Merge
1.5Deploying
1.5.1HerokuSetup
1.5.2HerokuDeployment,Step1
1.5.3HerokuDeployment,Step2
1.5.4HerokuCommands
1.6Conclusion
1.6.1WhatWeLearnedinThisChapter
1.7Exercises
Chapter2AToyApp
2.1PlanningtheApplication
2.1.1AToyModelforUsers
2.1.2AToyModelforMicroposts
2.2TheUsersResource
2.2.1AUserTour


2.2.2MVCinAction
2.2.3WeaknessesofThisUsersResource
2.3TheMicropostsResource
2.3.1AMicropostMicrotour
2.3.2PuttingtheMicroinMicroposts
2.3.3AUserhas_manyMicroposts
2.3.4InheritanceHierarchies
2.3.5DeployingtheToyApp
2.4Conclusion
2.4.1WhatWeLearnedinThisChapter
2.5Exercises

Chapter3MostlyStaticPages
3.1SampleAppSetup
3.2StaticPages
3.2.1GeneratedStaticPages
3.2.2CustomStaticPages
3.3GettingStartedwithTesting
3.3.1OurFirstTest
3.3.2Red
3.3.3Green
3.3.4Refactor
3.4SlightlyDynamicPages
3.4.1TestingTitles(Red)
3.4.2AddingPageTitles(Green)
3.4.3LayoutsandEmbeddedRuby(Refactor)
3.4.4SettingtheRootRoute
3.5Conclusion
3.5.1WhatWeLearnedinThisChapter
3.6Exercises
3.7AdvancedTestingSetup
3.7.1MiniTestReporters
3.7.2BacktraceSilencer
3.7.3AutomatedTestswithGuard
Chapter4Rails-FlavoredRuby
4.1Motivation
4.2StringsandMethods
4.2.1Comments


4.2.2Strings
4.2.3ObjectsandMessagePassing

4.2.4MethodDefinitions
4.2.5BacktotheTitleHelper
4.3OtherDataStructures
4.3.1ArraysandRanges
4.3.2Blocks
4.3.3HashesandSymbols
4.3.4CSSRevisited
4.4RubyClasses
4.4.1Constructors
4.4.2ClassInheritance
4.4.3ModifyingBuilt-inClasses
4.4.4AControllerClass
4.4.5AUserClass
4.5Conclusion
4.5.1WhatWeLearnedinThisChapter
4.6Exercises
Chapter5FillingintheLayout
5.1AddingSomeStructure
5.1.1SiteNavigation
5.1.2BootstrapandCustomCSS
5.1.3Partials
5.2SassandtheAssetPipeline
5.2.1TheAssetPipeline
5.2.2SyntacticallyAwesomeStyleSheets
5.3LayoutLinks
5.3.1ContactPage
5.3.2RailsRoutes
5.3.3UsingNamedRoutes
5.3.4LayoutLinkTests
5.4UserSign-up:AFirstStep

5.4.1UsersController
5.4.2Sign-upURL
5.5Conclusion
5.5.1WhatWeLearnedinThisChapter
5.6Exercises


Chapter6ModelingUsers
6.1UserModel
6.1.1DatabaseMigrations
6.1.2TheModelFile
6.1.3CreatingUserObjects
6.1.4FindingUserObjects
6.1.5UpdatingUserObjects
6.2UserValidations
6.2.1AValidityTest
6.2.2ValidatingPresence
6.2.3LengthValidation
6.2.4FormatValidation
6.2.5UniquenessValidation
6.3AddingaSecurePassword
6.3.1AHashedPassword
6.3.2UserHasSecurePassword
6.3.3MinimumPasswordLength
6.3.4CreatingandAuthenticatingaUser
6.4Conclusion
6.4.1WhatWeLearnedinThisChapter
6.5Exercises
Chapter7SignUp
7.1ShowingUsers

7.1.1DebugandRailsEnvironments
7.1.2AUsersResource
7.1.3Debugger
7.1.4AGravatarImageandaSidebar
7.2Sign-upForm
7.2.1Usingform_for
7.2.2Sign-upFormHTML
7.3UnsuccessfulSign-ups
7.3.1AWorkingForm
7.3.2StrongParameters
7.3.3Sign-upErrorMessages
7.3.4ATestforInvalidSubmission
7.4SuccessfulSign-ups
7.4.1TheFinishedSign-upForm


7.4.2TheFlash
7.4.3TheFirstSign-up
7.4.4ATestforValidSubmission
7.5Professional-GradeDeployment
7.5.1SSLinProduction
7.5.2ProductionWebServer
7.5.3RubyVersionNumber
7.6Conclusion
7.6.1WhatWeLearnedinThisChapter
7.7Exercises
Chapter8LogIn,LogOut
8.1Sessions
8.1.1SessionsController
8.1.2LoginForm

8.1.3FindingandAuthenticatingaUser
8.1.4RenderingwithaFlashMessage
8.1.5AFlashTest
8.2LoggingIn
8.2.1Thelog_inMethod
8.2.2CurrentUser
8.2.3ChangingtheLayoutLinks
8.2.4TestingLayoutChanges
8.2.5LoginuponSign-up
8.3LoggingOut
8.4RememberMe
8.4.1RememberTokenandDigest
8.4.2LoginwithRemembering
8.4.3ForgettingUsers
8.4.4TwoSubtleBugs
8.4.5“RememberMe”CheckBox
8.4.6RememberTests
8.5Conclusion
8.5.1WhatWeLearnedinThisChapter
8.6Exercises
Chapter9Updating,Showing,andDeletingUsers
9.1UpdatingUsers
9.1.1EditForm


9.1.2UnsuccessfulEdits
9.1.3TestingUnsuccessfulEdits
9.1.4SuccessfulEdits(withTDD)
9.2Authorization
9.2.1RequiringLogged-inUsers

9.2.2RequiringtheRightUser
9.2.3FriendlyForwarding
9.3ShowingAllUsers
9.3.1UsersIndex
9.3.2SampleUsers
9.3.3Pagination
9.3.4UsersIndexTest
9.3.5PartialRefactoring
9.4DeletingUsers
9.4.1AdministrativeUsers
9.4.2ThedestroyAction
9.4.3UserDestroyTests
9.5Conclusion
9.5.1WhatWeLearnedinThisChapter
9.6Exercises
Chapter10AccountActivationandPasswordReset
10.1AccountActivation
10.1.1AccountActivationsResource
10.1.2AccountActivationMailerMethod
10.1.3ActivatingtheAccount
10.1.4ActivationTestandRefactoring
10.2PasswordReset
10.2.1PasswordResetsResource
10.2.2PasswordResetsControllerandForm
10.2.3PasswordResetMailerMethod
10.2.4ResettingthePassword
10.2.5PasswordResetTest
10.3EmailinProduction
10.4Conclusion
10.4.1WhatWeLearnedinThisChapter

10.5Exercises
10.6ProofofExpirationComparison


Chapter11UserMicroposts
11.1AMicropostModel
11.1.1TheBasicModel
11.1.2MicropostValidations
11.1.3User/MicropostAssociations
11.1.4MicropostRefinements
11.2ShowingMicroposts
11.2.1RenderingMicroposts
11.2.2SampleMicroposts
11.2.3ProfileMicropostTests
11.3ManipulatingMicroposts
11.3.1MicropostAccessControl
11.3.2CreatingMicroposts
11.3.3AProto-feed
11.3.4DestroyingMicroposts
11.3.5MicropostTests
11.4MicropostImages
11.4.1BasicImageUpload
11.4.2ImageValidation
11.4.3ImageResizing
11.4.4ImageUploadinProduction
11.5Conclusion
11.5.1WhatWeLearnedinThisChapter
11.6Exercises
Chapter12FollowingUsers
12.1TheRelationshipModel

12.1.1AProblemwiththeDataModel(andaSolution)
12.1.2User/RelationshipAssociations
12.1.3RelationshipValidations
12.1.4FollowedUsers
12.1.5Followers
12.2AWebInterfaceforFollowingUsers
12.2.1SampleFollowingData
12.2.2StatsandaFollowForm
12.2.3FollowingandFollowersPages
12.2.4AWorkingFollowButtontheStandardWay
12.2.5AWorkingFollowButtonCreatedwithAjax


12.2.6FollowingTests
12.3TheStatusFeed
12.3.1MotivationandStrategy
12.3.2AFirstFeedImplementation
12.3.3Subselects
12.4Conclusion
12.4.1GuidetoFurtherResources
12.4.2WhatWeLearnedinThisChapter
12.5Exercises
Index


ForewordtotheFirstEdition
Myformercompany(CDBaby)wasoneofthefirsttoloudlyswitchtoRubyonRails,andtheneven
moreloudlyswitchbacktoPHP(Googlemetoreadaboutthedrama).ThisbookbyMichaelHartl
camesohighlyrecommendedthatIhadtotryit,andtheRubyonRails™TutorialiswhatIusedto
switchbacktoRailsagain.

ThoughI’veworkedmywaythroughmanyRailsbooks,thisistheonethatfinallymademe“get”
it.Everythingisdoneverymuch“theRailsway”—awaythatfeltveryunnaturaltomebefore,but
nowafterdoingthisbookfinallyfeelsnatural.ThisisalsotheonlyRailsbookthatdoestest-driven
developmenttheentiretime,anapproachhighlyrecommendedbytheexpertsbutwhichhasnever
beensoclearlydemonstratedbefore.Finally,byincludingGit,GitHub,andHerokuinthedemo
examples,theauthorreallygivesyouafeelforwhatit’sliketodoareal-worldproject.Thetutorial’s
codeexamplesarenotinisolation.
Thelinearnarrativeissuchagreatformat.Personally,IpoweredthroughtheRailsTutorialin
threelongdays,*doingalltheexamplesandchallengesattheendofeachchapter.Doitfromstartto
finish,withoutjumpingaround,andyou’llgettheultimatebenefit.
Enjoy!
—DerekSivers(sivers.org)
Founder,CDBaby
*[Authornote:]Thisisnottypical!Gettingthroughtheentirebookusuallytakesmuchlongerthanthreedays.


ForewordtotheThirdEdition
Railsisnowtenyearsoldandadoptionshowsnosignofslowingdown.Alongwiththeperpetual
growth,we’veseenaparadoxicaltragedyunfolding.Accordingtomanypeople,Railsisnowoneof
thehardesttechstacksforbeginnerstoadopt.Thecomplexityofchoicestomakewhenstartingoutis
veryhighandtherearetenyearsofblogpostsandbooksoutthere,mostofwhichareobsoleteand
brokentosomedegreeoranother.ThesupremeironyisthatgettingstartedwithRailstodayinvolves
alotofconfiguration,perhapsnotofRailsitself,butofthemyriadlibrariesthatarerecommended
forusewithit.Incaseyou’veforgotten,orweren’tpayingattentionin2005whenRailsdebuted,the
maingoalwastoachieveconventionoverconfiguration.
Tosomeextent,we’vereplicatedtheJavawebbeastthatweoncefoughthardtoslay.Argh.
Don’tgettoodepressedthough,becausethatwouldbemissingthepoint.Thegoodnewsisthat
onceyou’repastthedauntinglearningcurve,Railsremainsoneofthemostpowerfulandefficient
stacksavailableforbuildingAPIbackendsandcontent-drivenwebsites.
Nowmaybeyou’reconsideringusingthisbooktokickoffyourjourneyuptheRailslearning

curve.Trustme,it’stherightchoice.I’veknownMichaelHartlforalmosttenyearsnowandheisa
highlyintelligentman.Justlookforhiscredentialselsewhereinthebookandyou’llseewhatImean.
Butnevermindtheprestigiousdegrees,theapproachhehasadoptedforthislatesteditionofourbestsellingRubyonRails™Tutorialprovesjusthowsmartheis.Insteadofdoublingdownonthe
opinionatedapproach(likeanotherseriesauthorIknow,ahem),he’sgoneintheoppositedirection!
Bygettinglessopinionated,hehasloweredthebarrierforRailsnewcomersinsignificantways.
Firstofall,hedispenseswithanysortoflocalinstallationorconfiguration.Healsoeschews
complexconfigurationoptions(likeSporkandRubyTest),whicharelikelytotripupnovices.All
codeexamplesruninastandardizedcloud-basedenvironmentaccessibleviaasimplewebbrowser.
Second,hethrowsouttonsofcontentfromthepreviouseditionandembracestheRails“default
stack,”includingitsbuilt-inMiniTesttestingframework.Theresultingeliminationofmanyexternal
dependencies(RSpec,Cucumber,Capybara,FactoryGirl)makestheRailslearningcurvequiteabit
easiertoclimb,attheexpenseofhavingtorewritebigswathsofthebook.
Overtheyears,innosmallpartduetohisworkonthisbookfranchise,Michaelhasbecomea
masterofwritingtrainingmaterialsgroundedinpractical,usefulknowledge.Andasinthepast,this
editionincludesbasicsofvitaltoolssuchasGitandGitHub.Testingisfrontandcenter,whichmost
wouldagreeistheproperemphasisforbeginners.Michael’swell-polishedexamplesalwaysutilize
small,bite-sizedpiecesofcode—simpleenoughtounderstandandnovelenoughtobechallenging.
BythetimeyoufinishthebookandareplayingaroundwithyourveryownlittleTwitterclone,
you’resuretopossessadeeper,moreflexibleknowledgeofRails.Mostimportantly,you’llhavea
foundationflexibleenoughtogetyoucodingupnearlyanytypeofwebapplication.
Godspeed!
—ObieFernandez,
SeriesEditor


Acknowledgments
TheRubyonRails™TutorialowesalottomypreviousRailsbook,RailsSpace,andhencetomy
coauthorAureliusProchazka.I’dliketothankAurebothfortheworkhedidonthatbookandforhis
supportofthisone.I’dalsoliketothankDebraWilliamsCauley,myeditoronbothRailsSpaceand
theRubyonRails™Tutorial;aslongasshekeepstakingmetobaseballgames,I’llkeepwriting

booksforher.
I’dliketoacknowledgealonglistofRubyistswhohavetaughtandinspiredmeovertheyears:
DavidHeinemeierHansson,YehudaKatz,CarlLerche,JeremyKemper,XavierNoria,RyanBates,
GeoffreyGrosenbach,PeterCooper,MattAimonetti,MarkBates,GreggPollack,WayneE.Seguin,
AmyHoy,DaveChelimsky,PatMaddox,TomPreston-Werner,ChrisWanstrath,ChadFowler,Josh
Susser,ObieFernandez,IanMcFarland,StevenBristol,PratikNaik,SarahMei,SarahAllen,Wolfram
Arnold,AlexChaffee,GilesBowkett,EvanDorn,LongNguyen,JamesLindenbaum,AdamWiggins,
TikhonBernstam,RonEvans,WyattGreene,MilesForrest,thegoodpeopleatPivotalLabs,the
Herokugang,thethoughtbotguys,andtheGitHubcrew.Finally,many,manyreaders—fartoomany
tolist—havecontributedahugenumberofbugreportsandsuggestionsduringthewritingofthis
book,andIgratefullyacknowledgetheirhelpinmakingitasgoodasitcanbe.


AbouttheAuthor
MichaelHartlistheauthoroftheRubyonRails™Tutorial,oneoftheleadingintroductionstoweb
development,andisacofounderoftheSoftcoverself-publishingplatform.Hispriorexperience
includeswritinganddevelopingRailsSpace,anextremelyobsoleteRailstutorialbook,and
developingInsoshi,aonce-popularandnow-obsoletesocialnetworkingplatforminRubyonRails.
In2011,MichaelreceivedaRubyHeroAwardforhiscontributionstotheRubycommunity.Heisa
graduateofHarvardCollege,hasaPh.D.inPhysicsfromCaltech,andisanalumnusoftheY
Combinatorentrepreneurprogram.


Chapter1.FromZerotoDeploy
WelcometoRubyonRails™Tutorial:LearnWebDevelopmentwithRails.Thepurposeofthisbook
istoteachyouhowtodevelopcustomwebapplications,andourtoolofchoiceisthepopularRuby
onRailswebframework.Ifyouarenewtothesubject,theRubyonRails™Tutorialwillgiveyoua
thoroughintroductiontowebapplicationdevelopment,includingabasicgroundinginRuby,Rails,
HTMLandCSS,databases,versioncontrol,testing,anddeployment—sufficienttolaunchyouona
careerasawebdeveloperortechnologyentrepreneur.Ontheotherhand,ifyoualreadyknowweb

development,thisbookwillquicklyteachyoutheessentialsoftheRailsframework,includingMVC
andREST,generators,migrations,routing,andembeddedRuby.Ineithercase,whenyoufinishthe
RubyonRails™Tutorialyouwillbeinapositiontobenefitfromthemanymoreadvancedbooks,
blogs,andscreencaststhatarepartofthethrivingprogrammingeducationalecosystem.1
1.Themostup-to-dateversionoftheRubyonRails™Tutorialcanbefoundonthebook’swebsiteatIf
youarereadingthisbookoffline,besuretochecktheonlineversionoftheRailsTutorialbookat />forthelatestupdates.

TheRubyonRails™Tutorialtakesanintegratedapproachtowebdevelopmentbybuildingthree
exampleapplicationsofincreasingsophistication,startingwithaminimalhelloapp(Section1.3),a
slightlymorecapabletoyapp(Chapter2),andarealsampleapp(Chapter3throughChapter12).As
impliedbytheirgenericnames,theapplicationsdevelopedintheRubyonRails™Tutorialarenot
specifictoanyparticularkindofweb-site;althoughthefinalsampleapplicationwillbearmorethana
passingresemblancetoacertainpopularsocialmicrobloggingsite(asitethat,coincidentally,was
alsooriginallywritteninRails),theemphasisthroughoutthetutorialisongeneralprinciples,soyou
willhaveasolidfoundationnomatterwhichkindsofwebapplicationsyouwanttobuild.
Onecommonquestionishowmuchbackgroundisnecessarytolearnwebdevelopmentusingthe
RubyonRails™Tutorial.AsdiscussedinmoredepthinSection1.1.1,webdevelopmentisa
challengingsubject,especiallyforcompletebeginners.Althoughthetutorialwasoriginallydesigned
forreaderswithsomepriorprogrammingorwebdevelopmentexperience,infactithasfounda
significantaudienceamongbeginningdevelopers.Inacknowledgmentofthis,thethirdeditionofthe
RailsTutorialhastakenseveralimportantstepstowardloweringthebarriertogettingstartedwith
Rails(Box1.1).


Box1.1LoweringtheBarrier
ThisthirdeditionoftheRubyonRails™Tutorialaimstolowerthebarriertogettingstarted
withRailsinanumberofways:
•Useofastandarddevelopmentenvironmentinthecloud(Section1.2),whichsidestepsmanyof
theproblemsassociatedwithinstallingandconfiguringanewsystem
•UseoftheRails“defaultstack,”includingthebuilt-inMiniTesttestingframework

•Eliminationofmanyexternaldependencies(RSpec,Cucumber,Capybara,FactoryGirl)
•Alighter-weightandmoreflexibleapproachtotesting
•Deferraloreliminationofmorecomplexconfigurationoptions(Spork,RubyTest)
•LessemphasisonfeaturesspecifictoanygivenversionofRails,withgreateremphasison
generalprinciplesofwebdevelopment
ItismyhopethatthesechangeswillmakethethirdeditionoftheRubyonRails™Tutorial
accessibletoanevenbroaderaudiencethanpreviousversions.
Inthisfirstchapter,we’llgetstartedwithRubyonRailsbyinstallingallthenecessarysoftwareand
bysettingupourdevelopmentenvironment(Section1.2).We’llthencreateourfirstRailsapplication,
calledhello_app.TheRailsTutorialemphasizesgoodsoftwaredevelopmentpractices,so
immediatelyaftercreatingourfreshnewRailsprojectwe’llputitunderversioncontrolwithGit
(Section1.4).And,believeitornot,inthischapterwe’llevenputourfirstapponthewiderwebby
deployingittoproduction(Section1.5).
InChapter2,we’llmakeasecondproject,whosepurposeistodemonstratethebasicworkingsofa
Railsapplication.Togetupandrunningquickly,we’llbuildthistoyapp(calledtoy_app)byusing
scaffolding(Box1.2)togeneratethecode;becausethiscodeisbothuglyandcomplex,Chapter2will
focusoninteractingwiththetoyappthroughitsURIs(oftencalledURLs)2usingawebbrowser.
2.URIstandsforUniformResourceIdentifier,whiletheslightlylessgeneralURLstandsforUniformResourceLocator.Inpractice,
theURLisusuallyequivalentto“thethingyouseeintheaddressbarofyourbrowser.”

Therestofthetutorialfocusesondevelopingasinglelargerealsampleapplication(called
sample_app),writingallthecodefromscratch.We’lldevelopthesampleappusingacombination
ofmockups,test-drivendevelopment(TDD),andintegrationtests.We’llgetstartedinChapter3by
creatingstaticpagesandthenaddalittledynamiccontent.We’lltakeaquickdetourinChapter4to
learnalittleabouttheRubylanguageunderlyingRails.Then,inChapter5throughChapter10,we’ll
completethefoundationforthesampleapplicationbymakingasitelayout,auserdatamodel,anda
fullregistrationandauthenticationsystem(includingaccountactivationandpasswordresets).Finally,
inChapter11andChapter12we’lladdmicrobloggingandsocialfeaturestocreateaworking
examplesite.



Box1.2Scaffolding:Quicker,Easier,MoreSeductive
Fromthebeginning,Railshasbenefitedfromapalpablesenseofexcitement,startingwiththe
famous15-minuteweblogvideobyRailscreatorDavidHeinemeierHansson.Thatvideoand
itssuccessorsareagreatwaytogetatasteofRails’power,andIrecommendwatchingthem.
Butbewarned:Theyaccomplishtheiramazing15-minutefeatsusingafeaturecalled
scaffolding,whichreliesheavilyongeneratedcode,magicallycreatedbytheRailsgenerate
scaffoldcommand.
WhenwritingaRubyonRailstutorial,itistemptingtorelyonthescaffoldingapproach—
it’squicker,easier,moreseductive.Butthecomplexityandsheeramountofcodeinthe
scaffoldingcanbeutterlyoverwhelmingtoabeginningRailsdeveloper;youmaybeableto
useit,butyouprobablywon’tunderstandit.Followingthescaffoldingapproachrisksturning
youintoavirtuososcriptgeneratorwithlittle(andbrittle)actualknowledgeofRails.
IntheRubyonRails™Tutorial,we’lltakethe(nearly)polaroppositeapproach:Although
Chapter2willdevelopasmalltoyappusingscaffolding,thecoreoftheRailsTutorialisthe
sampleapp,whichwe’llstartwritinginChapter3.Ateachstageofdevelopingthesample
application,wewillwritesmall,bitesizedpiecesofcode—simpleenoughtounderstand,yet
novelenoughtobechallenging.Thecumulativeeffectwillbeadeeper,moreflexible
knowledgeofRails,givingyouagoodbackgroundforwritingnearlyanytypeofweb
application.

1.1Introduction
RubyonRails(orjust“Rails”forshort)isawebdevelopmentframeworkwrittenintheRuby
programminglanguage.Sinceitsdebutin2004,RubyonRailshasrapidlybecomeoneofthemost
powerfulandpopulartoolsforbuildingdynamicwebapplications.Railsisusedbycompaniesas
diverseasAirbnb,Basecamp,Disney,GitHub,Hulu,Kickstarter,Shopify,Twitter,andtheYellow
Pages.Inaddition,manywebdevelopmentshopsspecializeinRails,suchasENTP,thoughtbot,
PivotalLabs,Hashrocket,andHappyFunCorp,plusinnumerableindependentconsultants,trainers,
andcontractors.
WhatmakesRailssogreat?First,RubyonRailsis100%open-source,availableunderthe

permissiveMITLicense,andasaresultitcostsnothingtodownloadoruse.Railsalsoowesmuchof
itssuccesstoitselegantandcompactdesign;byexploitingthemalleabilityoftheunderlyingRuby
language,Railseffectivelycreatesadomain-specificlanguageforwritingwebapplications.Asa
consequence,manycommonwebprogrammingtasks—suchasgeneratingHTML,makingdata
models,androutingURLs—areeasywithRails,andtheresultingapplicationcodeisconciseand
readable.
Railsalsoadaptsrapidlytonewdevelopmentsinwebtechnologyandframeworkdesign.For
example,RailswasoneofthefirstframeworkstofullydigestandimplementtheRESTarchitectural
styleforstructuringwebapplications(whichwe’lllearnaboutthroughoutthistutorial).Andwhen
otherframeworksdevelopsuccessfulnewtechniques,RailscreatorDavidHeinemeierHanssonand
theRailscoreteamdon’thesitatetoincorporatetheirideas.Perhapsthemostdramaticexampleisthe
mergerofRailsandMerb,arivalRubywebframework,sothatRailsnowbenefitsfromMerb’s
modulardesign,stableAPI,andimprovedperformance.
Finally,Railsbenefitsfromanunusuallyenthusiasticanddiversecommunity.Theresultsinclude
hundredsofopen-sourcecontributors,well-attendedconferences,ahugenumberofgems(self-


containedsolutionstospecificproblemssuchaspaginationandimageupload),arichvarietyof
informativeblogs,andacornucopiaofdiscussionforumsandIRCchannels.Thelargenumberof
Railsprogrammersalsomakesiteasiertohandletheinevitableapplicationerrors:The“Googlethe
errormessage”algorithmnearlyalwaysproducesarelevantblogpostordiscussionforumthread.

1.1.1Prerequisites
Therearenoformalprerequisitestothisbook—theRubyonRails™Tutorialcontainsintegrated
tutorialsnotonlyforRails,butalsofortheunderlyingRubylanguage,thedefaultRailstesting
framework(MiniTest),theUnixcommandline,HTML,CSS,asmallamountofJavaScript,andeven
alittleSQL.That’salotofmaterialtoabsorb,though,andIgenerallyrecommendhavingsome
HTMLandprogrammingbackgroundbeforestartingthistutorial.Thatsaid,asurprisingnumberof
beginnershaveusedtheRubyonRails™Tutorialtolearnwebdevelopmentfromscratch,soevenif
youhavelimitedexperienceIsuggestgivingitatry.Ifyoufeeloverwhelmed,youcanalwaysgo

backandstartwithoneoftheresourceslistedinthissection.Anotherstrategyrecommendedby
multiplereadersissimplytodothetutorialtwice;youmaybesurprisedathowmuchyoulearnedthe
firsttime(andhowmucheasieritisthesecondtimethrough).
OnecommonquestionwhenlearningRailsiswhetheryoushouldlearnRubyfirst.Theanswer
dependsonyourpersonallearningstyleandhowmuchprogrammingexperienceyoualreadyhave.If
youprefertolearneverythingsystematicallyfromthegroundup,orifyouhaveneverprogrammed
before,thenlearningRubyfirstmightworkwellforyou.InthiscaseIrecommendLearntoProgram
byChrisPineandBeginningRubybyPeterCooper.However,manybeginningRailsdevelopersare
excitedaboutmakingwebapplicationsandwouldrathernotwaittofinishawholebookonRuby
beforeeverwritingasinglewebpage.Inthiscase,Irecommendfollowingtheshortinteractive
tutorialatTryRuby3togetageneraloverviewbeforestartingwiththeRailsTutorial.Ifyoustillfind
thistutorialtoodifficult,youmighttrystartingwithLearnRubyonRailsbyDanielKehoeorOne
MonthRails,bothofwhicharegearedmoretowardcompletebeginnersthantheRubyonRails™
Tutorial.
3. />
Attheendofthistutorial,nomatterwhereyoustarted,youshouldbereadyforthemanymore
intermediate-to-advancedRailsresourcesoutthere.HerearesomeIparticularlyrecommend:
•CodeSchool:Goodinteractive,onlineprogrammingcourses.
•TheTuringSchoolofSoftware&Design:Afull-time,27-weektrainingprograminDenver,
Colorado,witha$500discountforRailsTutorialreadersusingthecode
RAILSTUTORIAL500.
•TealeafAcademy:AgoodonlineRailsdevelopmentbootcamp(includesadvancedmaterial).
•Thinkful:Anonlineclassataboutthelevelofthistutorial.
•PragmaticStudio:OnlineRubyandRailscoursesfromMikeandNicoleClark.Alongwith
ProgrammingRubyauthorDaveThomas,MiketaughtthefirstRailscourseItook,waybackin
2006.
•RailsCastsbyRyanBates:Excellent(mostlyfree)Railsscreencasts.
•RailsApps:Alargevarietyofdetailedtopic-specificRailsprojectsandtutorials.
•RailsGuides:Topicalandup-to-dateRailsreferences.



1.1.2ConventionsinThisBook
Theconventionsinthisbookaremostlyself-explanatory.Inthissection,I’llmentionsomethatmay
notbe.
Manyexamplesinthisbookusecommand-linecommands.Forsimplicity,allcommand-line
examplesuseaUnix-stylecommand-lineprompt(adollarsign),asfollows:
$echo"hello,world"
hello,world

AsmentionedinSection1.2,Irecommendthatusersofalloperatingsystems(especiallyWindows)
useaclouddevelopmentenvironment(Section1.2.1),whichcomeswithabuilt-inUnix(Linux)
commandline.ThisisparticularlyusefulbecauseRailscomeswithmanycommandsthatcanberun
atthecommandline.Forexample,inSection1.3.2we’llrunalocaldevelopmentwebserverwiththe
railsservercommand:
$railsserver

Aswiththecommand-lineprompt,theRailsTutorialusestheUnixconventionfordirectory
separators(i.e.,aforwardslash/).Forexample,thesampleapplicationproduction.rb
configurationfileappearsasfollows:
Clickheretoviewcodeimag e
config/environments/production.rb

Thisfilepathshouldbeunderstoodasbeingrelativetotheapplication’srootdirectory,whichwill
varybysystem;onthecloudIDE(Section1.2.1),itlookslikethis:
Clickheretoviewcodeimag e
/home/ubuntu/workspace/sample_app/

Thus,thefullpathtoproduction.rbis
Clickheretoviewcodeimag e
/home/ubuntu/workspace/sample_app/config/environments/production.rb


Forbrevity,Iwilltypicallyomittheapplicationpathandwritejustconfig/environments/production.rb.
TheRailsTutorialoftenshowsoutputfromvariousprograms(e.g.,shellcommands,version
controlstatus,Rubyprograms).Becauseoftheinnumerablesmalldifferencesbetweendifferent
computersystems,theoutputyouseemaynotalwaysagreeexactlywithwhatisshowninthetext,but
thisisnotcauseforconcern.Inaddition,somecommandsmayproduceerrorsdependingonyour
system;ratherthanattempttheSisypheantaskofdocumentingallsucherrorsinthistutorial,Iwill
delegatetothe“Googletheerrormessage”algorithm,whichamongotherthingsisgoodpracticefor
real-lifesoftwaredevelopment.Ifyourunintoanyproblemswhilefollowingthetutorial,Isuggest
consultingtheresourceslistedintheRailsTutorialhelpsection.4
4. />
BecausetheRailsTutorialcoverstestingofRailsapplications,itisoftenhelpfultoknowifa
particularpieceofcodecausesthetestsuitetofail(indicatedbythecolorred)orpass(indicatedby


×