Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I like the condensing of code to</p> <pre><code>condition_string = Array.new(chapter_names.size, "chapters.name=?").join(" AND ") </code></pre> <p>and this does indeed work for a join with "OR".However the AND join will not work since this means that chapters.name in a single row of a join has to be both 'preface' and 'introduction' for example.</p> <p>An even neater way of doing my original "OR" join is</p> <pre><code> named_scope :has_chapter?, lambda { | chapter_names | {:joins =&gt; [: chapters] , :conditions =&gt; { :chapters =&gt; {:name =&gt; chapter_names}}} } </code></pre> <p>Thanks to Duplex on Rails Forum (<a href="http://railsforum.com/viewtopic.php?pid=103003#p103003" rel="nofollow noreferrer">Post link</a>) In order to achieve my original problem though DUPLEX suggested this</p> <pre><code>named_scope :has_chapters, lambda { |chapter_names| {:joins =&gt; :chapters , :conditions =&gt; { :chapters =&gt; {:name =&gt; chapter_names}}, :select =&gt; "books.*, COUNT(chapters.id) AS c_count", :group =&gt; "books.id", :having =&gt; "c_count = #{chapter_names.is_a?(Array) ? chapter_names.size : 1}" } } </code></pre> <p>This may work in some flavour of SQL but not in PostgreSQL. I had to use the following</p> <pre><code>named_scope : has_chapter?, lambda { | chapter_names | {:joins =&gt; :chapters , :conditions =&gt; { :chapters =&gt; {:name =&gt; chapter_names}}, :select =&gt; "books.* , COUNT(chapters.id)", :group =&gt; Book.column_names.collect{|column_name| "books.#{column_name}"}.join(","), :having =&gt; "COUNT(chapters.id) = #{chapter_names.is_a?(Array) ? chapter_names.size : 1}" } } </code></pre> <p>The code</p> <pre><code>Book.column_names.collect{|column_name| "books.#{column_name}"}.join(",") </code></pre> <p>is required because in PostgreSQL you can't select all columns with books.* and then GROUP BY books.* each column has to be named individually :(</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.
 

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