Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This seems to be the right way to do it:</p> <pre><code>attr_accessible :project_id </code></pre> <p>You don't have to put <code>:project</code> there, too! It's anyway possible to do <code>task.project=(Project.first!)</code></p> <p>Then check for the existence of the <code>:project_id</code> using the following (<code>:project_id</code> is also set when <code>task.project=(...)</code> is used):</p> <pre><code>validates :project_id, :presence =&gt; true </code></pre> <p>Now make sure than an associated Project is valid like this:</p> <pre><code>validates :project, :associated =&gt; true </code></pre> <p>So:</p> <pre><code>t = Task.new t.project_id = 1 # Value is accepted, regardless whether there is a Project with ID 1 t.project = Project.first # Any existing valid project is accepted t.project = Project.new(:name =&gt; 'valid value') # A new valid project is accepted t.project = Project.new(:name =&gt; 'invalid value') # A new invalid (or an existing invalid) project is NOT accepted! </code></pre> <p>It's a bit a pity that when assigning an ID through <code>t.project_id =</code> it's not checked whether this specific ID really exists. You have to check this using a custom validation or using the <a href="https://github.com/perfectline/validates_existence" rel="noreferrer">Validates Existence GEM</a>.</p> <p>To test these associations using RSpec with Remarkable matchers, do something like:</p> <pre><code>describe Task do it { should validate_presence_of :project_id } it { should validate_associated :project } end </code></pre>
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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