Search code examples
ruby-on-rails-3fields-for

Rails -- fields_for not working?


When I run the rails server and go to the school/new page on my site, the field with the label "school" where I can enter the school's name appears, but all the other fields under fields_for which are for entering the school administrator's info do not show up on my site -- when I use "inspect element" on my form it is like they are not even there. Why aren't they appearing on my page?

<%= form_for(@school) do |f| %>
  <% if @school.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@school.errors.count, "error") %> prohibited this school from being saved:</h2>

      <ul>
      <% @school.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :school %><br />
    <%= f.text_field :name %>
  </div>
  <%= f.fields_for :admin do |f2| %>
    <div class="field">
      <%= f2.label "administrator name" %><br />
      <%= f2.text_field :name %>
    </div>
    <div class="field">
      <%= f2.label "administrator email" %><br />
      <%= f2.text_field :email %>
    </div>
    <div class="field">
      <%= f2.label "administrator gender" %><br />
      <%= f2.text_field :gender %>
    </div>
  <% end %>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

Solution

  •  <%= f.fields_for :admin do |f2| %>
    

    try removing the f.

    try with just this:

    <%= fields_for :admin do |f2| %>
    

    There is two way to use field_for:

    A generic one. (like my example).

    A nested one.

    To use the nested field_for (f.field_for), your model object must be setup correctly

    Ex: Relation with @school and @admin

    class School< ActiveRecord::Base
      has_one :admin
      accepts_nested_attributes_for :admin
    end
    

    In the end, there is multiple ways of using field_for depending on how you setup the relations on your model object.

    This guide explain in details all the possible setup. You might find why it was not working for you.

    My bet is your Admin and School model object are not in a relation, or you didn't put the accepts_nested_attributes_for :admin in your School object.