I have model patient
. When patient
try to register, he fills fields, for example: name
, email
, telephone
, and there is validation presence
on this fields. Also i have another form in which doctor can add patient for himself, this form has only one field name
.
Question: can I somehow skip validation on fields email
and telephone
but leave validation on name
?
At the moment, i have this 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
When name
is present in params I skip validation and save patient, but when name
doesn't present, it will just render new
action with out error, and simple_form will not mark field in red color. Maybe there is way to raise error, or just another solution?
UPD
Solution: following the wintermeyer answer. As I have relation patient
belongs_to: doctor
, I can use - hidden_field_tag :doctor_id, value: @doctor.id
, and make check like guys said, unless: ->(patient){patient.doctor_id.present?}
.
P.S if someone use devise we should also skip devise required validation on email
and password
. We can add to model, in my case Patient
, something like this:
def password_required?
false if self.doctor_id.present?
end
def email_required?
false if self.doctor_id.present?
end