How to check that all children dates are before parent date?

Hello,

I have a Task model that uses acts_as_tree, giving me the parent_id. The
Task table has these columns:

1. name
2. due_on
3. parent_id

How would I validate that all children due dates (due_on) are inputted
before the parent task due date before it's saved?

(for example:
"debug project" due on May 1st - children task
"finish project" due on May 31st - parent task)

I'm thinking it might be something like this, but I'm sure I'm wrong:

  class Task < ActiveRecord::Base
    acts_as_tree
    validate :children_date_before_parent_date

    def children_date_before_parent_date
      errors.add_to_base("Children date must be before parent date") if
due_on <= parent.due_on
    end
  end

Any ideas?

Try something like this:

class Task < ActiveRecord::Base
  validate :date_check

  def date_check
    if self.parent_id
      errors.add(:due_on) if self.due_on > self.parent.due_on
    else
      errors.add_to_base("sub tasks have invalid dates") if
self.children.collect(&:due_on).any?{|date| date > self.due_on}
    end
  end
end

You can use the same function to validate that the child comes before
the parent AND that the parent doesn't contain any children that are
due after itself.

Andrew Bloom wrote:

Try something like this:

class Task < ActiveRecord::Base
  validate :date_check

  def date_check
    if self.parent_id
      errors.add(:due_on) if self.due_on > self.parent.due_on
    else
      errors.add_to_base("sub tasks have invalid dates") if
self.children.collect(&:due_on).any?{|date| date > self.due_on}
    end
  end
end

You can use the same function to validate that the child comes before
the parent AND that the parent doesn't contain any children that are
due after itself.

On May 10, 12:38�am, Bob Sanders <rails-mailing-l...@andreas-s.net>

It works perfectly! Thank you so much for your awesome help, Andrew. I
can't thank you enough. THANK YOU :slight_smile: