title: Conditional has_many in rails 2
body: <p>My app has applicants with many question_sections with many questions with many answers.</p>
  
  <p>Here I am returning these for an applicant</p>
  
  <pre><code>@question_sections = QuestionSection.find(
    :all, :include =&gt; {:questions =&gt; :answers},
    :conditions =&gt; ['answers.application_form_id is NULL OR answers.application_form_id = ?', @application_form.id],
    :order =&gt; 'question_sections.list_index ASC, questions.list_index ASC'
  )
  </code></pre>
  
  <p>What I'd like to do is return a row even if the answer row is null (ie, a left join on answer) so we can identify questions that have not been answered rather than omitting them entirely (which is what happens currently.)</p>
  
  <p>I think the issue might be that the answer belongs to both the question and the applicant;</p>
  
  <pre><code>class Answer &lt; ActiveRecord::Base 
  
    belongs_to :question
    belongs_to :application_form, :touch =&gt; true
  </code></pre>
  
  <p>So, is pseudo code I'd like 'belongs_to :application_form IF :application_form is not null' - to retain any potential associations.</p>
  
  <p>While I can write all this with SQL fairly easily, I'd like to let rails handle that and fix the model.</p>
  
  <p>In SQL I want to go from this</p>
  
  <pre><code>FROM `question_sections`
  LEFT OUTER JOIN `questions` ON questions.question_section_id = question_sections.id
  LEFT OUTER JOIN `answers` ON answers.question_id = questions.id
  WHERE ((answers.application_form_id IS NULL
          OR answers.application_form_id = 656))
  </code></pre>
  
  <p>to this</p>
  
  <pre><code>FROM `question_sections`
  LEFT OUTER JOIN `questions` ON questions.question_section_id = question_sections.id
  LEFT JOIN `answers` ON answers.question_id = questions.id AND answers.application_form_id = 656
  // No WHERE
  </code></pre>
  
  <p>Thanks.</p>
  
  <p><strong>EDIT</strong> </p>
  
  <p>What I need, I think, is a lambda on the has_many association. Something like;  </p>
  
  <pre><code>has_many :answers_and_null_answers, :whatever =&gt; lambda ( a = Answer.find(n); if a.nil? a = Answer.new; )
  </code></pre>
  
  <p>Obviously, thats just messy pseudo - but is this possible?</p>
  
  <p><strong>EDIT #2</strong> </p>
  
  <p>Aha! first_or_create does what I want, but seems you can'd do it on :includes. I'm assuming there is something I can do to the model to allow this?</p>