What does f.object do in Rails form builder?

I am learning Rails 5.0 from a tutorial, and in this tutorial it uses f.objectone that I am not familiar with. f.objectpassed to ERb in error handling method.

I know what fis the object / instance of the post submitted to the form. But I do not understand what it is f.object.

edit.html.erb (file with form):

<%= form_for(@section) do |f| %>

<%= error_messages_for(f.object) %>
  <table summary="Subject form fields">
    <tr>
      <th>Name</th>
      <td><%= f.text_field(:name) %></td>
    </tr>
    <tr>
      <th>Position</th>
      <td><%= f.select(:position, 1..@subject_count) %></td>
    </tr>
   </table>
<% end %>

There is no HTML form element known as object, and this is what usually happens after f., so it really looked like what it could be.

+4
source share
3 answers

f.object , form_for.

f.object @section.

+3

" f" - , . (@section), , , , . :

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

: _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 %> 

. html.

+3

:

f.object form_for , .

: @section

The code here inside is rails/actionview/lib/action_view/helpers/active_model_helper.rbapparently without comment:

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

Source: https://habr.com/ru/post/1666309/


All Articles