I am learning Rails 5.0 from a tutorial, and in that tutorial it uses f.object
, which I am unfamiliar with. The f.object
is being passed into ERb, into a method that handles error processing.
I know that f
is the object/instance of a record being passed into the form. But what I don't understand 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 that's what usually goes after the f.
, so really miffed on what it could be.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With