yoz*_*zzz 3 validation ruby-on-rails raiseerror
我有模型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
Run Code Online (Sandbox Code Playgroud)
当name
params 中存在时,我会跳过验证并保存患者,但是当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 如果有人使用 devise,我们还应该跳过 和 上的 devise 所需的email
验证password
。在我的例子中,我们可以添加到模型中Patient
,如下所示:
def password_required?
false if self.doctor_id.present?
end
def email_required?
false if self.doctor_id.present?
end
Run Code Online (Sandbox Code Playgroud)
小智 9
我喜欢做的是(在模型中):
attr_accessor :skip_validations
validates :name, presence: :true
validates :email, presence: :true, unless: :skip_validations
validates :telephone, presence: :true, unless: :skip_validations
Run Code Online (Sandbox Code Playgroud)
然后在控制器中:
patient = Patient.new(patient_params)
patient.skip_validations = true
Run Code Online (Sandbox Code Playgroud)
尽管它与其他答案相同,但我发现它更干净。
归档时间: |
|
查看次数: |
6854 次 |
最近记录: |