I have a form with nested attributes. I’m registering a student to a school and the student can have many emergency contacts.
class EmergencyContact < ActiveRecord::Base
attr_accessible :full_name, :relationship, :mobile_phone, :student_id
belongs_to :student
validates :full_name, :presence => true
validates :relationship, :presence => true
end
So I have a form to register the student and then 3 rows to enter the emergency contacts. Similar to the following (this is an oversimplified version of course…
Student Name: _____________
Emergency Contacts
------------------------------------------
| Name | Relationship |
------------------------------------------
| | |
------------------------------------------
| | |
------------------------------------------
| | |
------------------------------------------
If I only enter 2 emergency contacts, then I will get validation error that the name of the emergency contact can’t be blank. How can I make it NOT validate if all the fields in the form for that particual emergency contact are all blank?
I assume you have accepts_nested_attributes set up in your Student model. You need to add a :reject_if proc. It will ignore the row if the proc evaluates to true.
You could modify it to something like
lambda { |a| a[:name].blank? && a[:relationship].blank? }, etc. as your needs dictate.