我有模型 患者
。当患者
尝试注册时,他会填写字段,例如:name
、email
、telephone
,并且有在此字段上验证 presence
。我还有另一种表格,医生可以在其中为自己添加病人,这个表格只有一个字段name
。
问题:我能否以某种方式跳过对字段 email
和 telephone
的验证,但保留对 name
的验证?
目前,我有这个 Action :
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
,像男人一样做检查说,除非:->(患者){patient.doctor_id.present?}
。
P.S 如果有人使用设计,我们也应该跳过对 email
和 password
的设计所需验证。我们可以添加到模型中,在我的例子中是 Patient
,像这样:
def password_required?
false if self.doctor_id.present?
end
def email_required?
false if self.doctor_id.present?
end
最佳答案
我喜欢做的是(在模型中):
attr_accessor :skip_validations
validates :name, presence: :true
validates :email, presence: :true, unless: :skip_validations
validates :telephone, presence: :true, unless: :skip_validations
然后在 Controller 中:
patient = Patient.new(patient_params)
patient.skip_validations = true
虽然它和其他答案一样,但我觉得它更干净。
关于ruby-on-rails - 跳过少数字段的验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23591768/