我有一個Widgets模型。小部件屬於Store模型,屬於Area模型,屬於公司。在公司模型中,我需要找到所有關聯的小部件。易:Rails使用示波器擴展字段,PG不喜歡它
class Widget < ActiveRecord::Base
def self.in_company(company)
includes(:store => {:area => :company}).where(:companies => {:id => company.id})
end
end
將產生這個美麗的查詢:
> Widget.in_company(Company.first).count
SQL (50.5ms) SELECT COUNT(DISTINCT "widgets"."id") FROM "widgets" LEFT OUTER JOIN "stores" ON "stores"."id" = "widgets"."store_id" LEFT OUTER JOIN "areas" ON "areas"."id" = "stores"."area_id" LEFT OUTER JOIN "companies" ON "companies"."id" = "areas"."company_id" WHERE "companies"."id" = 1
=> 15088
不過,我以後需要在更復雜的範圍內使用這個範圍。問題在於AR通過選擇單個字段來擴展查詢,這些字段在PG中失敗,因爲所選字段必須位於GROUP BY子句或聚合函數中。
這是更復雜的範圍。
def self.sum_amount_chart_series(company, start_time)
orders_by_day = Widget.in_company(company).archived.not_void.
where(:print_datetime => start_time.beginning_of_day..Time.zone.now.end_of_day).
group(pg_print_date_group).
select("#{pg_print_date_group} as print_date, sum(amount) as total_amount")
end
def self.pg_print_date_group
"CAST((print_datetime + interval '#{tz_offset_hours} hours') AS date)"
end
,這是它是扔在PG選擇:
> Widget.sum_amount_chart_series(Company.first, 1.day.ago)
SELECT "widgets"."id" AS t0_r0, "widgets"."user_id" AS t0_r1,<...BIG SNIP, YOU GET THE IDEA...> FROM "widgets" LEFT OUTER JOIN "stores" ON "stores"."id" = "widgets"."store_id" LEFT OUTER JOIN "areas" ON "areas"."id" = "stores"."area_id" LEFT OUTER JOIN "companies" ON "companies"."id" = "areas"."company_id" WHERE "companies"."id" = 1 AND "widgets"."archived" = 't' AND "widgets"."voided" = 'f' AND ("widgets"."print_datetime" BETWEEN '2011-04-24 00:00:00.000000' AND '2011-04-25 23:59:59.999999') GROUP BY CAST((print_datetime + interval '-7 hours') AS date)
生成該錯誤:
PGError: ERROR: column "widgets.id" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: SELECT "widgets"."id" AS t0_r0, "widgets"."user_id...
如何重寫Widget.in_company範圍,使AR做不擴展選擇查詢以包含每個Widget模型字段?
Rails 3的可能?我曾在Rails3中/ Heroku的一個簡單的情況下,我沒有選擇特定的列 - 所以在做一個選擇*,然後得到這個錯誤 - 通過將特定的列選擇固定的 - 但你正在做的.... :( – 2011-05-20 07:28:44