Web Forms in Ruby on Rails

Share:

Listens: 0

Rails Coach

Technology


Building web forms in Rails was something that confused me when I was new to the framework. This is probably due to the fact that there are some methods that are a lot alike and there are a couple of ways of instantiating a form that do different things. The first way of building a form that is probably the most common is by using the ‘form_tag’ helper and the form helpers to build forms. Here’s an example. Pretty straightforward and it builds a standard login form. I’d get confused because there are also helpers that correspond to ‘label_tag’, ‘text_field_tag’, and ‘password_field_tag’ that do something very similar. Here’s a user signup form that use these similar tags: You’ll notice that these helpers use two parameters to build the form’s elements. It effectively scopes or namespaces those form parameters. They’ll be named “user[username]”, etc. If you’ve gotten that much, then ‘form_for’ won’t be too much of stretch. ‘form_for’ takes a model object as a parameter and binds the form to that object. It does the namespacing implicitly, which means that ‘label’ and ‘text_field’, etc don’t need two parameters to name the element. Just one. So, you’ll notice that the ‘form_for’ passes a parameter to the block. That parameter is a FormBuilder that contains the object, scopes the elements, and sets their values. Finally, go sign up for the Rails course at http://railscoach.com/ruby-on-rails-courses/.