我有两个模型,服务和约会。服务可以有很多约会。
我有一个嵌套表单供用户预约。
如何自动计算约会的结束时间?可以理解的是,我宁愿不依赖用户根据他们选择的服务长度输入结束时间。
目前我的控制器看起来像这样......
class AppointmentsController < ApplicationController
before_action :set_appointment, only: [:show, :edit, :update, :destroy]
before_action :load_services, only: [:new, :edit]
after_filter :end_calculate, only: [:create, :update]
[...]
# POST /appointments
# POST /appointments.json
def create
@appointment = Appointment.new(appointment_params)
respond_to do |format|
if @appointment.save
# redirect_to root_url
format.html { redirect_to @appointment, notice: 'Appointment was successfully created.' }
format.json { render :show, status: :created, location: @appointment }
else
format.html { render :new }
format.json { render json: @appointment.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /appointments/1
# PATCH/PUT /appointments/1.json
def update
respond_to do |format|
if @appointment.update(appointment_params)
format.html { redirect_to @appointment, notice: 'Appointment was successfully updated.' }
format.json { render :show, status: :ok, location: @appointment }
else
format.html { render :edit }
format.json { render json: @appointment.errors, status: :unprocessable_entity }
end
end
end
[...]
private
# Use callbacks to share common setup or constraints between actions.
def set_appointment
@appointment = Appointment.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def appointment_params
params.require(:appointment).permit(:start_time, :end_time, :note, :service_id)
end
def load_services
@services = Service.all.collect {|service| [ service.title, service.length, service.id] }
end
def end_calculate
@appointment.end_time = @appointment.start_time + @service.length.minutes
@appointment.end_time.save
end
end
答案 0 :(得分:1)
因此,在讨论之后,解决方案是从控制器中删除end_calculate
方法,并将end_time
方法添加到Appointment类:
def end_time
end_time = self.start_time + self.service.length.minutes
end