【问题标题】:ActiveRecord::RecordNotFound in BookingsController#create Couldn't find Appointment without an IDBookingsController#create 中的 ActiveRecord::RecordNotFound 找不到没有 ID 的约会
【发布时间】:2012-09-30 20:11:24
【问题描述】:

app/controllers/bookings_controller.rb:45:in `create'

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

我想创建一个具有 :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 时,正确的约会 ID 会通过 但我收到以下错误:

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

预订表格

<%= 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>

【问题讨论】:

  • 你的表单是什么样子的?
  • 你能告诉哪一行是控制器中的第 45 行吗?
  • 第 45 行在创建操作中:@appointment = Appointment.find(params[:appointment_id])

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


【解决方案1】:

您没有将 Appointment id 传递回 create 方法。

create 方法只知道从表单输入通过 params 哈希传入的信息。看到您还没有为appointment_id 的表单添加一个字段,它没有被传递给控制器​​并且在create 方法中不可用。

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

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

现在您通过表单发布显式传递 id,因此它将在您的控制器中可用。

【讨论】:

  • 感谢大卫的回复。我试过了,并且正在通过约会 ID,但它仍然给我同样的错误。知道它还能是什么吗?
  • appointment_id 参数将在您的booking 中,您是否尝试过像这样访问它:params[:booking][:appointment_id]
猜你喜欢
  • 1970-01-01
  • 2010-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多