我有模型patient。当patient尝试注册时,他会填写字段,例如:name、email、 telephone,并且presence在这些字段上进行验证。我还有另一种表格,医生可以在其中为自己添加病人,这个表格只有一个字段name。
问题:我可以以某种方式跳过字段验证email,telephone但保留验证name吗?
目前,我有这个动作:
def add_doctor_patient
@patient = @doctor.patients.new(patient_params)
if params[:patient][:name].present? and @patient.save(validate: false)
redirect_to doctor_patients_path(@doctor), notice: 'Added new patient.'
else
render action: 'new'
end
end
当name参数中存在时,我会跳过验证并保存患者,但当name不存在时,它只会呈现new操作而不会出现错误,并且 simple_form 不会将字段标记为红色。也许有办法引发错误,或者只是另一种解决方案?
UPD
解决方案:按照 Wintermeyer 的答案。由于我有关系patient belongs_to: doctor,我可以使用 - hidden_field_tag :doctor_id, value: @doctor.id,并像人们所说的那样进行检查,unless: ->(patient){patient.doctor_id.present?}。PS如果有人使用设计我们也应该跳过设计所需的验证email和password。在我的例子中,我们可以添加到模型中Patient,如下所示:
def password_required?
false if self.doctor_id.present?
end
def email_required?
false if self.doctor_id.present?
end