Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>EDIT: assuming that the association is not optional...</p> <p>The only way I can get it to thoroughly validate is this:</p> <pre><code>validates_associated :project validates_presence_of :project_id, :unless =&gt; Proc.new {|o| o.project.try(:new_record?)} validates_presence_of :project, :if =&gt; Proc.new {|o| o.project_id} </code></pre> <p>The first line validates whether the associated Project is valid, if there is one. The second line insists on the <code>project_id</code> being present, unless the associated Project exists and is new (if it's a new record, it won't have an ID yet). The third line ensures that the Project is present if there is an ID present, i.e., if the associated Project has already been saved.</p> <p>ActiveRecord will assign a <code>project_id</code> to the task if you assign a saved Project to <code>project</code>. If you assign an unsaved/new Project to <code>project</code>, it will leave <code>project_id</code> blank. Thus, we want to ensure that <code>project_id</code> is present, but only when dealing with a saved Project; this is accomplished in line two above.</p> <p>Conversely, if you assign a number to <code>project_id</code> that represents a real Project, ActiveRecord will fill in <code>project</code> with the corresponding Project object. But if the ID you assigned is bogus, it will leave <code>project</code> as nil. Thus line three above, which ensures that we have a <code>project</code> if <code>project_id</code> is filled in -- if you supply a bogus ID, this will fail.</p> <p>See RSpec examples that test these validations: <a href="https://gist.github.com/kianw/5085085" rel="nofollow">https://gist.github.com/kianw/5085085</a></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.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      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