I have a flights table and passengers table. When creating a new flight I need to be able to add multiple passengers to that flight.
I have managed to join my flights and passengers tables and the passengers are now showing up in the new flight form. The problem now is that I can't seem to save the passengers.
Flight form:
<label><%= form.label :passengers %></label>
<%= collection_select(:passenger, :passenger_id, Passenger.all, :id, :first_name, {}, { :multiple => true } )%>
flight.rb
has_and_belongs_to_many :passengers
passenger.rb
has_and_belongs_to_many :flights
flights_controller.rb
def create
@flight = Flight.new(flight_params)
params[:passenger][:passenger_ids].each do |passenger_id|
unless passenger_id.empty?
passenger = Passenger.find(passenger_id)
@flight.passengers << passenger
end
end
respond_to do |format|
if @flight.save
format.html { redirect_to @flight, notice: 'Flight was successfully created.' }
format.json { render :show, status: :created, location: @flight }
else
format.html { render :new }
format.json { render json: @flight.errors, status: :unprocessable_entity }
end
end
end
schema.rb
create_table "flights", force: :cascade do |t|
t.string "origin"
t.string "destination"
t.string "dep_time"
t.string "arr_time"
t.integer "seats"
t.integer "price"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "airline_id"
t.index ["airline_id"], name: "index_flights_on_airline_id"
end
create_table "flights_passengers", id: false, force: :cascade do |t|
t.integer "flight_id", null: false
t.integer "passenger_id", null: false
t.index ["flight_id", "passenger_id"], name: "index_flights_passengers_on_flight_id_and_passenger_id"
t.index ["passenger_id", "flight_id"], name: "index_flights_passengers_on_passenger_id_and_flight_id"
end
create_table "passengers", force: :cascade do |t|
t.string "first_name"
t.string "last_name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
You should add passengers to the flight before saving, like this:
@flight.passengers << passenger
You are adding it to the @boarding
, can't see where you have declared that?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.