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
It seems to be such a simple question but the longer I think about it the more possible solutions come up. I have a hard time to tell which one is the DRYest. The quick and dirty solution would be to add a hidden boolean field xyz
in the doctor's form. You'd have to add that attribute on the bottom of your controller if you are using Rails 4. With that you could do something like this in your model:
validates :name, presence: true
validates :email, presence: true, unless: ->(patient){patient.xyz.present?}