2

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 %>
Antarr Byrd
  • 24,863
  • 33
  • 100
  • 188
Kyle Bachan
  • 1,053
  • 2
  • 15
  • 33

2 Answers2

8

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.

user229044
  • 232,980
  • 40
  • 330
  • 338
  • Ohhhhh right, completely forgot about that. Been so long since I've used vanilla Ruby, that I forgot about that bit. – Kyle Bachan Jul 28 '14 at 18:03
3

Because it takes a block argument.

It doesn't have anything to do with looping, e.g., File#open also takes a block.

#open yields the opened file. The form_for helper yields the helper.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302