我正在尝试以下代码:
class AppointmentsController < ApplicationController
def create
@appointment = Appointment.new(params[:appointment])
@current_patient = @appointment.patient_id
if @appointment.save
flash[:success] = "Appointment scheduled!"
redirect_to patient_path(@current_patient)
else
render 'patients/show'
end
end
目前正在通过三个控制器。其中两个似乎很重要。
class Appointment < ActiveRecord::Base
attr_accessible :appointment_date, :appointment_notes, :appointment_time, :procedure_id, :patient_id
belongs_to :patient
belongs_to :procedure
validates :procedure_id, presence: true
validates :patient_id, presence: true
validates :appointment_date, presence: true
validates :appointment_time, presence: true
class Patient < ActiveRecord::Base
attr_accessible :address1, :address2, :city, :comment, :email, :first_name, :init_date, :init_time, :last_name, :mobile, :notes, :phone, :state, :zip
before_validation :upcase_patient
before_save { self.email.downcase! }
has_many :appointments, dependent: :destroy
has_many :procedures, through: :appointments
我的创建方法非常棒。但是,当我提交数据并且未在约会中传递验证时,它应该呈现正确的app.dev/patients/:id页面,其中:id是我正在使用的当前页面。有问题的表格是创建约会的表格(通过Patient / show视图)。当提交不正确或零数据并且存在:true时,我希望呈现相同的页面。我目前收到的是:
rspec的
ActionView::Template::Error:
undefined method `first_name' for nil:NilClass
# ./app/views/patients/show.html.erb:1:in `_app_views_patients_show_html_erb__4137167421928365638_70201005779320'
# ./app/controllers/appointments_controller.rb:11:in `create'
我怀疑这与能够相应地在正确的路径上设置渲染有关,特别是调用正确的患者/ id。任何帮助将不胜感激。
答案 0 :(得分:1)
您最可能的问题是,您在patients/show
中使用的变量在验证失败并且您呈现模板时未在create动作中声明。解决此问题的最佳方法是,如果验证失败,则在create action上声明show动作上使用的同一组变量
def show
@patients = ...
@files = ...
end
def create
if @object_that_fails_validation.save
else
@patient = ...
@files = ...
#render the show action
end
end
如果您认为这不是DRY,尤其是当您声明了很多变量时,可以通过ajax提交表单或将变量移动到其他方法
def show
set_variables
end
def create
if @object_that_fails_validation.save
else
set_variables
#render the show action
end
end
protected
def set_variable
@patient = ...
@files = ...
end