考虑将您的 SQL 语句显示为视图,并创建一条新记录以与视图交互。
这是一个我支持 AR 的项目:
https://github.com/michaelkirk/household-account-mgmt/blob/develop/app/models/monthly_report.rb
class CreateMonthlyReports < ActiveRecord::Migration
def up
sql = <<-SQL
create view monthly_reports as
select date_part('year', created_at) as year, date_part('month', created_at) as month, sum(purchase_amount) as purchases_amount, sum(investment_amount) as investments_amount
from (
select * from transactions
left join
(select id as purchase_id, amount as purchase_amount from transactions where credit = false)
as purchases on transactions.id = purchases.purchase_id
left join
(select id as investment_id, amount as investment_amount from transactions where credit = true)
as investments on transactions.id = investments.investment_id)
as classified_transactions
group by year, month
order by year, month
SQL
execute(sql)
end
def down
sql = <<-SQL
drop view monthly_reports
SQL
execute(sql)
end
然后,由于您已将复杂性抽象到数据库视图中,就 AR 的所有意图/目的而言,它就像一个表格,您的模型和控制器看起来完全是普通的。
class MonthlyReport < ActiveRecord::Base
MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
def time_period
"#{month} #{year}"
end
def month
MONTHS[self[:month] - 1]
end
def year
self[:year].to_i
end
end
然后你可以做类似的事情
class MonthlyReportsController < ApplicationController
def index
@monthly_reports = MonthlyReport.all
end
end
请注意,由于这是一个 DB 视图,您将无法进行插入操作。我不确定如果你尝试会发生什么。