Note that there are some explanatory texts on larger screens.

plurals
  1. PORails 3 using select distinct
    primarykey
    data
    text
    <p>I have 3 tables I need to join together.</p> <p>I have <code>Events</code>, <code>Places</code>, and <code>Boroughs</code></p> <p>Places belong to a Borough and have many Events</p> <p>From a list of events on a given day, I would like to retrieve a list of all the distinct boroughs.</p> <pre><code>Event.where(day_of_week: 2).joins(:place,:borough).select("DISTINCT(boroughs.name) AS name") </code></pre> <p>Generating the SQL:</p> <pre><code>SELECT DISTINCT(boroughs.name) AS name FROM "events" INNER JOIN "places" ON "places"."id" = "events"."place_id" INNER JOIN "places" "places_events_join" ON "places_events_join"."id" = "events"."place_id" INNER JOIN "boroughs" ON "boroughs"."id" = "places_events_join"."borough_id" WHERE "events"."active" = 't' AND "events"."day_of_week" = 3 </code></pre> <p>Which looks perfect and works when I throw it into my postgres DB console, however for my rails console I get.</p> <pre><code>#&lt;Event &gt;, #&lt;Event &gt;, #&lt;Event &gt;, #&lt;Event &gt;, #&lt;Event &gt;, #&lt;Event &gt;, #&lt;Event &gt;, #&lt;Event &gt;, #&lt;Event &gt;, #&lt;Event &gt; </code></pre> <p>UPDATE: </p> <p>Mr.The Walrus' suggestion works perfectly, but I'm still confused why going the other way around doesn't work when the SQL itself produces the same result.</p> <pre><code>Borough.joins(:events).where(:events =&gt; {:day_of_week =&gt; 2}).select("DISTINCT(boroughs.name) AS name") </code></pre> <p>Produces: </p> <pre><code>[#&lt;Borough name: "richmond"&gt;, #&lt;Borough name: "southwark"&gt;, #&lt;Borough name: "brent"&gt;, #&lt;Borough name: "city of london"&gt;] </code></pre> <p>But this</p> <pre><code>Event.where(:events =&gt; {:day_of_week =&gt; 2}).joins(:borough).select("DISTINCT(boroughs.name) AS name") </code></pre> <p>Produces:</p> <pre><code>[#&lt;Event &gt;, #&lt;Event &gt;, #&lt;Event &gt;, #&lt;Event &gt;, #&lt;Event &gt;] </code></pre>
    singulars
    1. This table or related slice is empty.
    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.
 

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