Home > Mobile >  Rails nested form only adding one Passenger Object to a Booking
Rails nested form only adding one Passenger Object to a Booking

Time:09-16

The form below renders the correct HTML so a user can enter multiple passenger information into a form, yet when i debug to see what the form is submitting it only has 1 passenger's details when there could be up to 4 passengers per booking.

<%= form_for @booking do |f| %>
  <% params[:passengers].to_i.times do %>
    <%= f.fields_for @passenger do |addy_form|%>
      <%= addy_form.text_field :name, placeholder: "name" %>
      <%= addy_form.text_field :email, placeholder: "email"%>
    <% end %>
  <% end %>

  <%= hidden_field_tag(:flight_id, params[:flight_id]) %>
  <%= hidden_field_tag(:scheduled_for, params[:scheduled_for]) %>
  <%= hidden_field_tag(:from_airport, params[:from_airport]) %>
  <%= hidden_field_tag(:to_airport, params[:to_airport]) %>

   <%= f.submit 'Confirm Booking' %>
<% end %>

Booking Controller

class BookingsController < ApplicationController
  def new
    @booking = Booking.new
    @passenger = Passenger.new
  end
end

EDIT: added params below that the form is submitting. In the form I added 2 passenger's details, 1) John - [email protected] 2) sarah - [email protected]

{"authenticity_token"=>"egDf-wifNMx4PzXQdFNpv_3NXnRyWp007D8klnMu-D3Hc47vKUVmJc1ehs-8RcV8SPapPG-bVPSTqLeu9M-A-w", "booking"=>{"passenger"=>{"name"=>"sarah", "email"=>"[email protected]"}}, "flight_id"=>"9", "scheduled_for"=>"2021-02-10 23:15:00 UTC", "from_airport"=>"1", "to_airport"=>"2", "commit"=>"Confirm Booking", "controller"=>"bookings", "action"=>"create"}

CodePudding user response:

That is because you are overriding the value of @Passenger multiple times with the new value entered.

You should initialize passengers in the controller.

class BookingsController < ApplicationController
  def new
    @booking = Booking.new
    params[:passengers].to_i.times do 
      @booking.passengers.build
    end
  end
end

and update the view to be like the main docs using @booking.passengers

CodePudding user response:

With guidance from Magzy's answer and also I missed out adding this to my booking model:

accepts_nested_attributes_for :passengers
  • Related