Starting on Page 73 of Head First Rails, we need to add an index page so that people can find the pages they want!
First, let’s add a new route so that http://localhost/index.cfm/ads/ goes to the new index action we’ll add in a minute.
Open up /config/routes.cfm, and change it to:
<cfset addRoute(name="ads", pattern="/ads/[key]", controller="ads", action="show")>
<cfset addRoute(name="adsNoKey", pattern="/ads/", controller="ads", action="index")>
<cfset addRoute(name="catchall", pattern="[path]", controller="redirect", action="index")>
<cfset addRoute(name="home", pattern="", controller="redirect", action="index")>
Notice the new route on line 2: <cfset addRoute(name=”adsNoKey”, pattern=”/ads/”, controller=”ads”, action=”index”)>. CFWheels checks the routes in order. So, if the URL pattern matches /ads/[key], it will go to the show action. But, if the key isn’t there, it matches the /ads/ pattern and goes to the new index action.
Now, we need to add an index action to the controller and then an index.cfm view. Open up /controllers/Ads.cfc and add the new index function. Leave the show function alone.
Notice the that we set ads = model(“Ad”).findAll(). This tells Wheels, to go get the Ad model, and findAll the data — Pretty Powerful! The data comes back as a ColdFusion query object.
For testing, put the <cfdump>line in your controller, and send your browser to: http://localhost/index.cfm/ads/. You’ll see the query dumped out in all its glory! This is a pretty good debugging trick. Add a <cfdump> to your controller to see what variables and data the controller is passing to the view. Remove the <cfdump> line, and let’s go create the view.
Go create /views/ads/index.cfm:
Pretty simple! Specifying the query attribute in <cfoutput> makes this just like a <cfloop>. You end up with a bunch of List Items (<li>) — One for each record in the query we got from the controller.
linkTo() is another cool Wheels helper function. You could just use an <a> tag. However, using the linkTo() function is a best practice because it makes your application more portable. We specified the “ads” route in the function. If, later on, we changed our subfolders or URL rewriting, everything would still work.
That’s it. Send your browser to: http://localhost/index.cfm/ads/ and you should see a list of ads. Each ad will have a link that takes you to the show action and displays the ad.