Search code examples
ruby-on-railsrubyform-helpersdo-loops

Why does the Rails form helper look like a do loop?


Here's a question I've been meaning to ask for a long time, but have just accepted it as "Rails magic" up to this point. As the title states, why does the Rails form helper look like a do loop? If you check the official Rails documentation, it doesn't seem to explain this, it just jumps right in by giving the below as a basic example:

<%= form_tag do %>
  Form contents
<% end %>

So what's going on here exactly? Why does the form appear to be creating a loop as opposed to input forms in other languages that do not have said loop.

<%= form_for @person, url: {action: "create"} do |person_form| %>
  <%= person_form.text_field :name %>
  <%= fields_for @person.contact_detail do |contact_details_form| %>
    <%= contact_details_form.text_field :phone_number %>
  <% end %>
<% end %>

Solution

  • That's not "Rails magic", that's completely vanilla Ruby syntax. do/end denote a block in Ruby, not a loop.

    Rails' documentation doesn't explain this, because Rails' documentation assumes a knowledge of Ruby. Rails does not introduce any new syntax (nor can it), it's just a framework, written in 100% plain old Ruby.