In this eighth part of a series on the Action Pack library for Rails, you will learn how to handle request parameters and how to use the render method. This article is excerpted from chapter six of the book Beginning Rails: From Novice to Professional, written by Jeffery Allan Hardy, Cloves Carneiro Jr. and Hampton Catlin (Apress; ISBN: 1590596862).
You already know that, by default, when an action hascompleted, it will attempt to render a template of the same name.Sometimes you want to render a different template, though.
In thecreateaction we just created, if email@example.com, we want to set a friendlyflashmessage and redirect. However, if thesavefails, we want to render thenewtemplate. If we didnít explicitly rendernew, the action would fall through to its default behavior and attempt to render a template namedcreate, which, of course, doesnít exist.
Therendermethod takes several options for its first argument::text,:nothing,:inline, and:update.
Note The:updateresponse is fairly specialized. You use it when youíre rendering Ajax responses, as youíll learn in Chapter 7.
It might not sound like it, but a redirection is aresponse. Redirects donít really happen on the server side. Instead, aresponse is sent to your browser that tells it to perform a redirectionto another URL. The specifics of issuing a redirect arenít somethingyou need to worry about, though, since Rails provides a specializedmethod to take care of the internals. That method is called redirect_to, and itís one youíll find yourself using a lot, so itís a good idea to get familiar with it.
As you can see from the example in thecreate action,redirect_totakes a hash of options. Most of the time, youíll specify the name of acontroller, action, or both. The current controller is presumed unlessa controller value is given, so in our case, Rails will redirect to theindexaction in theuserscontroller. You can also pass aroundparameters when redirecting; any key/value pairs you append to theredirect will be parameterized and become part of theparamshash.
Please check back for the next part of this series.
DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.