title: named_scope in rails with a has_many association
body: <p>I am trying to achieve what I think will be a fairly complex query using the magic of Rails without having lots of ugly looking SQL in the code.</p>
  
  <p>Since my database is dealing with rather specialised biomedical models I'll translate the following to a more real world scenario. </p>
  
  <p>I have a model Book that</p>
  
  <p>has_many :chapters</p>
  
  <p>and Chapter that </p>
  
  <p>belongs_to :book</p>
  
  <p>Say for instance Chapters have a name attribute and the names can be  preface ,introduction and appendix, and a Book could have a Chapter named preface and a Chapter named introduction but no Chapter named appendix. In fact any combination of these</p>
  
  <p>I am looking to find all Books that have both Chapters named preface and introduction.</p>
  
  <p>At present I have a named_scope as follows</p>
  
  <pre><code>Book
    named_scope :has_chapter?, lambda { |chapter_names|
      condition_string_array = []
      chapter_names.size.times{condition_string_array &lt;&lt; "chapters.name = ?"}
      condition_string = condition_string_array.join(" OR ")
      {:joins =&gt; [:chapters]  , :conditions =&gt; [condition_string, * chapter_names]}
    }
  </code></pre>
  
  <p>If I call Book. has_chapter? ["preface", "introduction"] this will find me all books that have either a Chapter named preface or introduction. How could I do a similar thing that would find me isolates that <strong>both</strong> Chapters preface and introduction?</p>
  
  <p>I am not that familiar with SQL so am not quite sure what kind of join would be needed and whether this could be achieved in a named scope.</p>
  
  <p>Many thanks</p>
  
  <p>Anthony</p>