What does f.object do in the Rails form builder?

f.object refers to the object passed as an argument to the form_for method.

In your example f.object returns @section.


"f" is the local variable used in the form block. The form contains an object (@section) and if an error occurs you pass that object to an error partial that checks if there are any errors and renders the error messages the object created for you. In my form I usually add an error partial like this:

  <%= render "shared/error_messages", object: f.object %>

In your error partial it looks somewhat like this (_error_messages.html.erb):

<% if object.errors.any? %>   # object in this case is @section
  <ul>
    <% object.errors.full_messages.each do |msg| %>
    <li><%= msg %></li>
    <% end %>
  </ul>
</div>
<% end %> 

It really is just a way to pass the form's object with is errors to a partial to display it properly. There is no html involved.


As explained in these two questions :

f.object inside the form_for returns the model object the form is using.

In this case : @section

The code is here, inside rails/actionview/lib/action_view/helpers/active_model_helper.rb, apparently without comments :

    module ActiveModelInstanceTag
      def object
        @active_model_object ||= begin
          object = super
          object.respond_to?(:to_model) ? object.to_model : object
        end
      end
      ...