Note that there are some explanatory texts on larger screens.

plurals
  1. POValidate presence of nested attributes
    primarykey
    data
    text
    <p>How do I validate that a model has at least one associated model using nested attributes? This has been driving me crazy as I am sure that I am missing something simple. For example, I want to require that a List always has at least one Task.</p> <pre><code>class List &lt; ActiveRecord::Base has_many :tasks, :dependent =&gt; :destroy accepts_nested_attributes_for :tasks, :allow_destroy =&gt; true end class Task &lt; ActiveRecord::Base belongs_to :list end </code></pre> <p>I've tried many different options.</p> <p>1- adding a validation to lists:</p> <pre><code>def validate if self.tasks.length &lt; 1 self.errors[:base] &lt;&lt; "A list must have at least one task." end end </code></pre> <p>but this will still allow you to delete all the tasks of an <strong>existing</strong> list since when deleting tasks the validation of list happens before the tasks are destroyed.</p> <p>2- checking to see if any tasks are not marked for destruction in a before_save callback</p> <pre><code>before_save :check_tasks private #look for any task which won't be deleted def check_tasks for t in self.tasks return true if ! t.marked_for_destruction? end false end </code></pre> <p>For some reason I can't get it to ever delete a task with anything that iterates over a list's tasks. The same is true if I do this check in <code>def validate</code> instead of a callback</p> <p>3- requiring the presence of tasks <code>validates_presence_of :tasks</code>, but with this it won't ever delete any tasks</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload