Clifton Labrum
Clifton Labrum

Reputation: 14060

Nested Rails Form Fields Not Rendering

I have read a number of posts about this and I'm still confused. I'm relatively new to Rails. I'm on Rails 3.2.8 and Ruby 1.9.3.

I have a form where I want to create a record for 2 different tables. It's a many-to-many relationship (logbooks can have multiple aircraft and aircraft will appear in multiple logbooks).

Here's my code:

# ----- Models ----- #
class Logbook < ActiveRecord::Base
  has_and_belongs_to_many :aircrafts
  accepts_nested_attributes_for :aircrafts
end

class Aircraft < ActiveRecord::Base
  belongs_to :logbook
end

# ----- Logbooks Controller ----- #
def my_method
  @logbook = Logbook.new 
  @aircraft = Aircraft.new
end

# ----- View ----- #
<%= form_for @logbook, validate: true, remote: true do |f| %>
  <%= f.label :flight_date, "Flight Date" %>
  <%= f.text_field :flight_date %>  
  ...

  <%= f.fields_for :aircrafts, validate: true, remote: true do |a| %>
    <%= a.label :aircraft_id, "Aircraft ID" %>
    <%= a.text_field :aircraft_id %>
    ...
  <% end %>
<% end %>

The logbook fields are rendering fine, but the aircraft fields don't render.

Any ideas?

Upvotes: 1

Views: 908

Answers (2)

daniloisr
daniloisr

Reputation: 1367

Try changing the controller to:

def my_method
  @logbook = Logbook.new 
  @aircraft = @logbook.aircrafts.build
end

Because @aircraft need belongs_to a Logbook, so the nested_form will know how to build the form.

Note: if you will not use the variable @aircraft you don't need to declare it, just use @logbook.aircrafts.build on controller

Upvotes: 2

agmcleod
agmcleod

Reputation: 13611

If i recall correctly, the fields_for will generate based off the number of objects in the has many that exist for the parent. Since your @logbook doesn't have any aircrafts, no fields appear. Try changing the action:

def my_method
  @logbook = Logbook.new
  @logbook.aircrafts << Aircraft.new
end

Now, if you need to make something in the UI to add more than one logbook, you need to create an add button. You can just increment the amount of aircraft records you build based off that:

<%= form_tag new_logbook_path, :method => :get do %>
  <%= hidden_field_tag "amount", @amount %>
  <%= submit_tag "Add" %>
<% end %>

Then the action would be:

def my_method
  @amount = params[:amount] || 1
  @logbook = Logbook.new
  @amount.times { @logbook.aircrafts << Aircraft.new }
end

Upvotes: 0

Related Questions