Ruby on Rails: How to validate nested attributes on certain condition?

First of all, I want to be sure that you mean blank? rather than present?. Typically, I see this:

validate :address, :presence_of => true, :if => 'organisation.present?'

Meaning, you only want to validate address if organisation is also present.

Regarding, :accepts_nested_attributes_for, are you using this feature by passing in nested form attributes, or some such thing? I just want to make sure you absolutely need to use this functionality. If you are not actually dealing with nested form attributes, you can implement cascading validation using:

validates_associated :address

If you do need to use :accepts_nested_attributes, be sure to check out the :reject_if parameter. Basically, you can reject adding an attribute (and it's descendants) altogether if certain conditions apply:

accepts_nested_attributes_for :address, :allow_destroy => true, :reject_if => :no_organisation

def no_organisation(attributes)
  attributes[:organisation_id].blank?
end

Now, if none of the above apply, let's take a look at your syntax:

It should work, :if/:unless take symbols, strings and procs. You don't need to point to the foreign_key, but can simplify by pointing to:

:if => "organisation.blank?"

You have other validations in the Address model, correct? Is Address being validated when you don't want it to? Or is Address not being validated? I can help you test it out in the console if you can give me some additional details.


  1. To make things easier for myself re: mass-assignment, I changed the rails config: config.active_record.whitelist_attributes = false
  2. I created a gist for you to follow along
  3. I have a sample project as well. Let me know if you are interested.

    Basic points:

  4. Added the following to Person to ensure that either Org or Address are valid:

    validates_presence_of :organisation, :unless => "address.present?" validates_associated :address, :unless => "organisation.present?"

  5. Added validation to Address to trigger errors when Org is not present: validates_presence_of :line1, :line2, :city, :zip

    I was able to produce the requirements you are seeking. Please look at the gist I created where I have a full console test plan.


I added a controller file to the previous gist.

Overview:

  1. All you should need to create the person is: @person = current_user.people.build(params[:person])
  2. :organisation_id will always be found off of the :person param node, like so: params[:person][:organisation_id] So you're if will never be true.

I updated the gist with the necessary changes to the controller, the model and the form.

Overview:

  1. You need to cleanup your controller. You are using accepts_nested_attribute, so in the :create, you only care about params[:person]. Additionally, in the render :new, you need to setup any instance variables that the partial will use. This does NOT go back through the :new action. The :new and :edit actions also need to be simplified.
  2. Your Person model needs to use the :reject_if argument because the Address fields are coming back to the :create action as :address_attributes => {:line1 => '', :line2 => '', etc}. you only want to create the association if any have values. Then your validates_presence_of for :organisation will work just fine.
  3. Your form needs to pass the organisation id to the controller, rather than the organisation names

    It's all in the gist


Should be the final gist.

Overview:

  1. Add the following to your edit action right after building the @person:

    @person.build_address if @person.address.nil? This ensure that you have the address inputs, even if the @person.address does not exist. It doesn't exist, because of the :reject_if condition on accepts_nested_attributes

  2. I DRYed up the :reject_if as follows. It's a little hacky, but has some utility:

    accepts_nested_attributes_for :address, :allow_destroy => true, :reject_if => :attributes_blank?
    
    def attributes_blank?(attrs)  
      attrs.except('id').values.all?(&:blank?)  
    end  
    

    a. attrs -> the result of params[:person][:address]
    b. .except('id') -> return all key-values except for 'id'
    c. .values -> return all values from a hash as an array
    d. .all? -> do all elements in the array satisfy the following check
    e. &:blank -> ruby shorthand for a block, like this: all?{ |v| v.blank? }