BookingsController中的ActiveRecord :: RecordNotFound #create无法找到没有ID的约会

时间:2012-09-30 20:11:25

标签: ruby-on-rails ruby-on-rails-3 activerecord

app / controllers / bookings_controller.rb:45:在'create'

我有一个Appointments对象和一个Bookings对象。预订属于Appointments和Appointments has_many预订。

我想创建一个预约对象,其中包含:appointment_id

这是我的代码:

<% @appointments.each do |appointment| %>
    <%= link_to "new Booking", new_appointment_booking_path(appointment)%>
<%end%>

预订控制器:

def new
    @appointment = Appointment.find(params[:appointment_id])
    @booking = @appointment.bookings.new 
    ...

 def create
I was missing [:booking] in line 45. 
 Line 45:   @appointment = Appointment.find(params[:booking][:appointment_id])
     @booking = @appointment.bookings.new(params[:booking])

路由

resources :appointments do
    resources :bookings
end

当我提交Bookings_form时,会传递正确的appointment_id 但我收到以下错误:

ActiveRecord::RecordNotFound in BookingsController#create
Couldn't find Appointment without an ID

预订_form

<%= simple_form_for(@booking) do |f| %>
  <%= f.error_notification %>

  <div class="form-inputs">
    <%= f.input :appointment_date %>
    <%= f.input :start_time %>
    <%= f.input :end_time %>
    <%= f.input :name %>
    <%= f.input :phone_number %>
    <%= f.hidden_field :appointment_id%>  

 <div class="form-actions">
     <%= f.button :submit %>
  </div>

1 个答案:

答案 0 :(得分:1)

您没有将约会ID传回create方法。

create方法除了从表单输入通过params哈希传入的信息外什么都不知道。如果您没有在appointment_id的表单中添加字段,则它不会传递给控制器​​,并且在create方法中不可用。

要解决此问题,请在表单中添加一个新的隐藏输入,如下所示:

<%= f.input :appointment_id, :type => :hidden %>

现在您明确地将id传递给表单帖子,因此它将在您的控制器中可用。