hfhc2
hfhc2

Reputation: 4391

Nested forms in rails 4 and the fields_for method

I am also having problems with nested forms and Rails 4 (this seems to be quite common unfortunately). I have events which have requirements, the models are:

class Event < ActiveRecord::Base
  enum type: [:lecture, :exercise, :tutorial]

  has_one :requirement, dependent: :destroy

  #accepts_nested_attributes_for :requirement
end

and

class Requirement < ActiveRecord::Base
  belongs_to :event
end

There is essentially a one-to-one correspondence between those two. Now I would like to create a new event together with the associated requirement. I am using the following form:

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

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

  <div class="container">
    <%= f.select :type, Event.types.map { |key, value| [key.humanize, key] }%>
    <%= f.text_field :number, placeholder: "1298035" %>

    <% f.fields_for :requirement, @event.requirement do |fields| %>
      <%= fields.check_box :beamer %><br />
    <% end %>

    <%= f.submit %>
  </div>
  <% end %>
</div>

As you can see I would like to have a checkbox indicating whether a beamer is required. The problem is that the fields_for block is never evaluated. Similar to these posts:

Rails 3: fields_for showing blank filed on Edit view

Helper "fields_for" not working

As far as I can tell the objects are created properly:

  # GET /events/new
    def new
      @event = Event.new
      @event.build_requirement
    end

If I use puts I see that both objects are not nil and that the associations are correct.

I am kind of new to rails and I must say that I'm stymied. Any ideas?

Upvotes: 0

Views: 420

Answers (1)

Pavan
Pavan

Reputation: 33542

You should uncomment accepts_nested_attributes_for :requirement in the Event model.

Update:

You should also include = in the fields_for.

<%= f.fields_for :requirement, @event.requirement do |fields| %>

Upvotes: 2

Related Questions