Ruby on Rails Logo

Ruby on Rails – Forms

I have been learning Ruby on Rails for about two weeks and so far I really enjoyed learning Sinatra more. Rails is so massive and magical. It is almost too magical and does everything it can for you. The “magic” makes understanding what is going on at a low level difficult. In Sinatra, it is left to you to do everything and there is very little “magic”. I think the more I learn about Rails, it will grow on me. Or at least, I am hoping that it will.

# Rails form_for Helper
# Auto Generating a HTML Form

<%= form_for @article do |f| %>
  <%= f.label 'Article Title' %><br>
  <%= f.text_field :title %><br>
  <%= f.label 'Article Description' %><br>
  <%= f.text_area :description %><br>
  <%= f.submit "Submit Article" %>
<% end %>

With the magical code above, a Ruby object is being passed to the form_for method. The Ruby object we are passing is an instance of the Article class. If the article object has attributes for title and description already, Rails will pre-populate those values in the generated HTML. If the article’s title and description attributes are nil, there will be no values populated in the HTML text fields.

Beyond pre-populating, Rails also knows which route to use for the form action. If the attributes are nil, we must be wanting to create a new article. If the attributes on @article are not nil, Rails assumes we are updating the object.

The labels and text fields are generated using the Rails FormBuilder object. This FormBuilder object is yielded from the form_for method (the f variable above) and is associated with the article object. f.label is a FormBuilder method that will return a string of HTML, which will be a label tag.

Rails get quite complex quickly and it is not immediately clear what is happening. Although the form_for code above looks very simple, it is doing a lot behind the scenes.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.