leonel
leonel

Reputation: 10214

Rails 3. Don't validate nested attributes if all left blank

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?

Upvotes: 2

Views: 5928

Answers (2)

akarzim
akarzim

Reputation: 141

You could also modify it to something more generic like

proc { |attributes| 
    attributes.delete :_destroy
    attributes.reject { |key, value| value.blank? }.empty?
}

EDIT

You can also do this in an easiest way

accepts_nested_attributes_for :emergency_contacts, :reject_if => :all_blank

You can find some documentation here : http://api.rubyonrails.org

Upvotes: 7

niiru
niiru

Reputation: 5102

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.

class Student < ActiveRecord::Base 
  has_many                      :emergency_contacts
  accepts_nested_attributes_for :emergency_contacts, 
                                :reject_if => lambda { |a| a[:full_name].blank? }
end

You could modify it to something like lambda { |a| a[:name].blank? && a[:relationship].blank? }, etc. as your needs dictate.

Upvotes: 10

Related Questions