我在下拉字段中显示一个小时数组
[["09:30am", "2013-02-14 09:30:00"], ["10:00am", "2013-02-14 10:00:00"] ...
我使用:
渲染数组<%= f.select :atime, @time_options %>
我将数组的值赋给控制器中的实例变量
def new
@time_options = Appointment.time_options
@doctor = Doctor.find(params[:doctor_id])
@appointment = @doctor.schedule.appointments.build
end
# GET /appointments/1/edit
def edit
@time_options = Appointment.time_options
@doctor = Doctor.find(params[:doctor_id])
@appointment = @doctor.appointments.find(params[:id])
end
# POST /appointments
# POST /appointments.json
def create
@time_options = Appointment.time_options
@doctor = Doctor.find(params[:doctor_id])
@appointment = @doctor.schedule.appointments.new(params[:appointment])
if @appointment.save
#send email
AppointmentMailer.appointment_confirmation(@appointment, I18n.locale).deliver
AppointmentMailer.new_appointment(@appointment, I18n.locale).deliver
redirect_to :action => 'thank_you'
else
render action: 'new'
end
end
在模型中我定义了一个构建数组的类方法
def self.time_options
start_of_day = Time.zone.now.beginning_of_day
start_time = start_of_day + 9.hours
end_time = start_of_day + 17.hours
lunch_start = start_of_day + 13.hours
lunch_end = start_of_day + 14.hours + 30.minutes
times = []
until start_time > end_time
start_time = (start_time + 30.minutes)
unless start_time >= lunch_start && start_time < lunch_end
times << start_time
end
end
times.map{|t| [t.strftime("%I:%M%p").downcase, t.to_s(:db)] }
end
但是,当我提交表单时,我会看到undefined method
为空?&#39;对于nil:NilClass`错误:
<%= f.select :atime, @time_options %>
我做错了什么?
答案 0 :(得分:3)
这个
<%= f.select :atime, @time_options %>
应该是这样的
<%= f.select :atime_id, @time_options %>
答案 1 :(得分:2)
在create
方法中,从@doctor
开始,然后沿着链:调度,然后params[:appointment]
,直到找到nil,然后弄清楚为什么它为零。如果你正在运行rails,那么Rails.logger或pry将成为你的朋友。