Rails returns NoMethodError in Bookings#create Showing /home/mwenyewe/TOP/Fullstack_Ruby_on_Rails/Ruby_on_Rails/flight-booker/app/views/bookings/new.html.erb where line #3 raised:undefined method `id' for nil:NilClass当我尝试提交乘客详细信息时。这是我的Booking new.html.erb
<%= form_with model: @booking do |form| %>
<%= form.label :flight, 'Flight ID' %>
<%= form.text_field :flight, value: @flight.id, readonly: true, disabled: true %>
<%= form.hidden_field :flight_id, value: @flight.id %>
<%= form.label :date, 'Date' %>
<%= form.text_field :date, value: @flight.start, readonly: true, disabled: true %><br>
<%= form.label :departure_airport, 'Departure Airport' %>
<%= form.text_field :departure_airport, value: @flight.departure_airport.code, readonly: true, disabled: true %>
<%= form.label :arrival_airport, 'Arrival Airport' %>
<%= form.text_field :arrival_airport, value: @flight.arrival_airport.code, readonly: true, disabled: true %><br>
<% @booking.passengers.each do |passenger| %>
<%= form.fields_for :passengers_attributes, passenger do |p| %>
<%= p.hidden_field :id, value: p.object.id %>
<%= p.label :name %>
<%= p.text_field :name %>
<%= p.label :email %>
<%= p.email_field :email %><br><br>
<% end %>
<% end %>
<%= form.submit %><br>
<% end %>
表格的第一部分应该显示乘客选择的航班细节。第二个表单允许用户输入乘客详细信息。这是我的控制器:
class BookingsController < ApplicationController
def new
@booking = Booking.new
@flight = Flight.find(params[:flight_id])
params[:tickets].to_i.times{ @booking.passengers.build }
end
def create
@booking = Booking.new(booking_params)
if @booking.save
redirect_to flights_path
else
render :new, status: :unprocessable_entity
end
end
private
def booking_params
params.require(:booking).permit(:flight_id, passengers_attributes: [:id, :name, :email])
end
end
下面是Flight索引视图,它应该发送flight_id:
<%= form_with url: new_booking_path, method: :get do |f| %>
<% @found_flights.each do |flight| %>
<%= f.radio_button :flight_id, flight.id %>
<%= f.label "flight_#{flight.id}" do %>
From: <%= flight.departure_airport.code %>
To: <%= flight.arrival_airport.code %>
Date: <%= flight.start.to_fs(:long) %>
Tickets: <%= request.query_parameters[:flight][:tickets] %>
<% end %>
<%= f.hidden_field :tickets, value: request.query_parameters[:flight][:tickets] %>
<% end %>
<%= f.submit 'Select Flight' %>
<% end %>
我已经试着按照参数传递,但一切似乎都在做它的工作。即使没有传递flight_id,它也会向用户显示航班的详细信息。
1条答案
按热度按时间oymdgrw71#
我发现我的模特们都很臃肿,是罪魁祸首,虽然我不知道是怎么回事,但我还没有找到答案。以下是我编辑之前的模型:
现在这里是之后:
正如你所看到的,我把它修剪下来,试图找到bug。我仍然不知道它是如何导致的错误,但我喜欢我的应用程序没有错误。如果有经验的人能告诉我是什么导致了这个bug,我将不胜感激。