Form Helpers in Rails...Shudder
One of the more frustrating experiences I've had as a beginning rails developer is figuring out the form helper. When I first encountered it, I immediately wondered what the point of it was. Why do I need this, my html forms work perfectly fine? I think the reason I clung to my html forms was because it was one of the few things I was familiar with, and with all the new stuff I was learning, I held tight the few familiar things I had to work with. Now that I understand what's going on in Rails a little better, I'm prepared to admit that form helpers are indeed extremely useful.
form method="post" action="/hats" input type="hidden" value= %= session[:_csrf_token] % name="authenticity_token" input type="submit" value="Generate Match List" /form
That little piece of beauty was my come to Jesus moment. For this button I passed in a Ruby CSRF token as a value, which was a good catch on my part as it ensured the button was protected from cross site request forgery. But the way I did it is pretty silly if you know that with a simple form helper, the CSRF token is passed in automatically (as long as the default security feature is enabled). Here is a basic form_tag, followed by the html it automatically generates:
%= form_tag do % Form stuff % end % form accept-charset="UTF-8" action="/home/index" method="post" div input name="utf8" type="hidden" value="✓" input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" Form stuff /div /form
Why it has to put those div tags in there I'm not sure, but according to the Rails Guides they are necessary to send the data. Another one of my forms contained radio buttons and a text field:
%= radio_button_tag(:participating-yes) % %= label_tag(:yes, "Yes") % %= radio_button_tag(:participating-no) % %= label_tag(:no, "No") % %= text_field_tag(:interests) %
These helpers generate the necessary html input attributes to pass form data as a ruby object directly to it's route.
input id="participating-yes" name="age" type="radio" value="true" label for="yes" Yes /label input id="participating-no" name="age" type="radio" value="adult" label for="no" Yes /label input id="interests" name="interests" type="text"
Needless to say, that's incredibly handy. A similar helper exists for every form control in HTML. Here is a list of other helpers of interest and the html they generate. And here is a nice cheatsheet to remember exactly how form helpers work. There have been about a dozen other little things like this where I've had to relearn how something works for the sake of efficiency/ making things less breakable. Embracing a new approach is tough and it slows you down at first, but it's usually worth the effort. I'll be using form helpers in all my rails apps going forward.













