We’re on Page 52 of Head First Rails, and we need to create a custom Controller and View.
I’m going to keep following the book, but there is a great tutorial that covers the same ideas over on the CFWheels website.
Convention Rules! CFWheels has conventions for almost everything. As long as you follow the conventions, things just work naturally.
For example, look at a URL like this http://localhost/ads/show/5. CFWheels will automatically interpret this to run the show function in the ads controller. The number 5 is passed as a “key”.
Before I keep going, I have to touch on URL rewriting. The URL I just used as an example will only work if your server supports full URL rewriting. I’m using the ColdFusion development server, and it only offers “partial” URL rewriting. So, I have to use a URL like this: http://localhost/index.cfm/ads/show/5. Notice that index.cfm has to be inserted in the URL!
You can also specify the Controller and Action like this: http://localhost/index.cfm?controller=ads&action=show&key=5. Doing it this way will always work. It bypasses routes and any server URL rewriting problems. You might want to just use this form of URL while you are learning or if you are debugging a problem.
In any case, the idea is to run the show function in the ads controller. CFWheels will look for Ads.cfc in the controller folder, and will look for the show function inside Ads.cfc.
Then, it will run the show function and load the view. It will expect there to be a view file in /views/ads named show.cfm to match the function you called.
But, guess what? If you don’t create the Ads.cfc controller, CFWheels, will still try to run the view. Normally, you’ll want the controller to get some data for you, but if not, you could skip the controller altogether.
Here’s my controller code for /controllers/Ads.cfc:
Later, we’ll add some functionality to the controller, but I’m following the book. And, for now, the only two actions we need are index and show.
At this point, you could try to go to http://localhost/index.cfm?controller=ads&action=show&key=5. But, you’d get a Wheels error because there is no view file.
Here’s my view code for /views/ads/show.cfm:
I know, this doesn’t do much either, but we’ll add on. Be Patient!
Now, if you go to http://localhost/index.cfm?controller=ads&action=show&key=5, you’ll see the lovely static view file you just created.
Next time, we’ll look at routes some more, and eventually, we’ll actually make this app work.