我有 3 张桌子需要连接在一起。
我有Events
,Places
和Boroughs
地方属于自治市镇并有许多活动
从给定日期的事件列表中,我想检索所有不同行政区的列表。
Event.where(day_of_week: 2).joins(:place,:borough).select("DISTINCT(boroughs.name) AS name")
生成 SQL:
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
当我将它放入我的 postgres DB 控制台时,它看起来很完美并且可以工作,但是对于我的 rails 控制台,我得到了。
#<Event >, #<Event >, #<Event >, #<Event >, #<Event >, #<Event >, #<Event >, #<Event >, #<Event >, #<Event >
更新:
Mr.The Walrus 的建议非常有效,但我仍然很困惑,为什么当 SQL 本身产生相同的结果时,反过来却行不通。
Borough.joins(:events).where(:events => {:day_of_week => 2}).select("DISTINCT(boroughs.name) AS name")
产生:
[#<Borough name: "richmond">, #<Borough name: "southwark">, #<Borough name: "brent">, #<Borough name: "city of london">]
但是这个
Event.where(:events => {:day_of_week => 2}).joins(:borough).select("DISTINCT(boroughs.name) AS name")
产生:
[#<Event >, #<Event >, #<Event >, #<Event >, #<Event >]