Reputation: 1301
I display an array of hours in a dropdown field
[["09:30am", "2013-02-14 09:30:00"], ["10:00am", "2013-02-14 10:00:00"] ...
I render the array with:
<%= f.select :atime, @time_options %>
I assign the values of the array to the instance variable in the controller
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
And in the model I have defined a class method to build the array
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
However when I submit the form, i get a undefined method
empty?' for nil:NilClass` error on:
<%= f.select :atime, @time_options %>
What I'm doing wrong?
Upvotes: 1
Views: 8287
Reputation: 922
This
<%= f.select :atime, @time_options %>
should be like this
<%= f.select :atime_id, @time_options %>
Upvotes: 3
Reputation: 1240
In the create
method, start with the @doctor
and go down the chain: schedule, then params[:appointment]
, until you find the nil, then figure out why it's nil. Rails.logger or pry if you're running rails s will be your friend.
Upvotes: 2