AsafirstapplicationoftheMVCframework,wellmakeawaferthinchangetothefirstappbyaddingacontroller
actiontorenderthestringhello,world!toreplacethedefaultRailspagefromFigure1.10. (Welllearnmoreabout
controlleractionsstartinginSection2.2.2.)
Asimpliedbytheirname,controlleractionsaredefinedinsidecontrollers. Wellcallouractionhelloandplaceitinthe
Applicationcontroller. Indeed,atthispointtheApplicationcontrolleristheonlycontrollerwehave,whichyoucan
verifybyrunning
$ ls app/controllers/*_controller.rb
Havingdefinedanactionthatreturnsthedesiredstring,weneedtotellRailstousethatactioninsteadofthedefault
pageinFigure1.10. Todothis,welledittheRailsrouter,whichsitsinfrontofthecontrollerinFigure1.11and
determineswheretosendrequeststhatcomeinfromthebrowser. (IveomittedtherouterfromFigure1.11forsimplicity,
butwelldiscussitinmoredetailstartinginSection2.2.2.) Inparticular,wewanttochangethedefaultpage,theroot
route,whichdeterminesthepagethatisservedontherootURL. BecauseitstheURLforanaddresslike
http://www.example.com/(wherenothingcomesafterthefinalforwardslash),therootURLisoftenreferredtoas/
(slash)forshort.
AsseeninListing1.9,theRailsroutesfile(config/routes.rb)includesacommentdirectingustotheRailsGuideon
Routing,whichincludesinstructionsonhowtodefinetherootroute. Thesyntaxlookslikethis:
root 'controller_name#action_name'
Inthepresentcase,thecontrollernameisapplicationandtheactionnameishello,whichresultsinthecodeshown
inListing1.10.
Listing1.9: Thedefaultroutingfile(formattedtofit).
c o n f i g / r o u t e s . r b
Rails.application.routes.draw do
# For details on the DSL available within this file,
# see http://guides.rubyonrails.org/routing.html
end
Listing1.10: Settingtherootroute.
c o n f i g / r o u t e s . r b
Rails.application.routes.draw do
root 'application#hello'
end
WiththecodefromListing1.8andListing1.10,therootroutereturnshello,world!asrequired(Figure1.12).16 Hello,
world!
Figure1.12: Viewinghello,world!inthebrowser.
Exercises
1.ChangethecontentofthehelloactioninListing1.8toreadhola,mundo!insteadofhello,world!.
2.ShowthatRailssupportsnonASCIIcharactersbyincludinganinvertedexclamationpoint,asinHola,mundo!
(Figure1.13).17 TogetacharacteronaMac,youcanuseOption1otherwise,youcanalwayscopyandpastethe
characterintoyoureditor.
3.ByfollowingtheexampleofthehelloactioninListing1.8,addasecondactioncalledgoodbyethatrendersthetext
goodbye,world!. EdittheroutesfilefromListing1.10sothattherootroutegoestogoodbyeinsteadof
tohello(Figure1.14).
Figure1.13: ChangingtherootroutetoreturnHola,mundo!.
Figure1.14: Changingtherootroutetoreturngoodbye,world!.