我们有很多的 report 是由 SQL 直接生成的
class SaleReport < ActiveRecord::Base
#...
self.table_name = "sale_report"
#..。
end
这个 sale_report 是一个 postgresql view,由 10 个以上 table join 生成的,大概这个样子:
SELECT
table_a.id,
#省略若干
FROM abstract_table_a table_a
LEFT JOIN table_u table_u ON table_u.id = table_a.payer_id
AND table_a.payer_type = 'Farmer'
LEFT JOIN table_b table_b ON table_b.id = table_a.order_item_id
#省略若干LEFT JOIN
AND table_c.archived_at IS NULL
AND table_c.staff_id IS NOT NULL
LEFT JOIN users table_d ON table_d.p_id = orders.p_id
AND table_d.archived_at IS NULL
LEFT JOIN table_f table_f ON table_b.p_id = table_f.id
AND table_b.p_type = 'SUV'
LEFT JOIN table_l table_f_category ON table_f_category.id = table_f.table_l_id
LEFT JOIN table_g table_g ON table_b.p_id = table_g.id
AND table_b.p_type = 'CAR'
LEFT JOIN table_l table_g_category ON table_g_category.id = table_g.table_l_id
LEFT JOIN table_h ON table_b.p_id = table_h.id
AND table_b.p_type = 'TRUCK'
LEFT JOIN table_r ON table_h.treatment_id = table_r.id
LEFT JOIN table_l table_h_category
ON table_h_category.id = table_r.table_l_id
LEFT JOIN (
#省略若干行
) AS table_x ON table_a.id = table_x.inv_id
LEFT JOIN (
SELECT #省略若干行
FROM #省略若干行
INNER JOIN #省略若干行
WHERE#省略若干行
) table_Z ON table_a.id = table_Z.inv_id
WHERE #省略若干行
ORDER BY #省略若干行;
我希望的是能在 rspec 中,就像用 facotrybot 一样能够
let!(:report) {create(:sale_report)}
我尝试过创建
factory :sale_report, class: SaleReport do
但得到 error
ActiveRecord::StatementInvalid: PG::ObjectNotInPrerequisiteState: ERROR: cannot insert into view "sale_report"
DETAIL: Views that do not select from a single table or view are not automatically updatable.
HINT: To enable inserting into the view, provide an INSTEAD OF INSERT trigger or an unconditional ON INSERT DO INSTEAD rule.
: INSERT INTO "sale_report" DEFAULT VALUES RETURNING "id"
现在如果想要写这个 report 的单元测试需要一个个的 creat join table 的 instance,非常的耗时,而且需要先理解 tables 之间的关系。
请问有什么思路吗?有什么 gem 可以帮助实现吗