Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip validation on few fields

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
like image 444
yozzz Avatar asked Mar 31 '26 05:03

yozzz


2 Answers

What I like to do is (in the model):

attr_accessor :skip_validations

validates :name, presence: :true
validates :email, presence: :true, unless: :skip_validations
validates :telephone, presence: :true, unless: :skip_validations

then in the controller:

patient = Patient.new(patient_params)
patient.skip_validations = true

Altough it does the same as the other answers I find it cleaner.

like image 70
Mathieu Larouche Avatar answered Apr 02 '26 19:04

Mathieu Larouche


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?}
like image 20
wintermeyer Avatar answered Apr 02 '26 18:04

wintermeyer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!