下面的代码用作Postgre查询,我试图在我的rails应用程序中调用它并将其分配给一个对象:@agent_monthly_performance。
SELECT user_id AS user_id,
to_char(created_at,'Mon-YY') AS year_month,
sum(total_amount) AS amount,
sum(total_lm) AS lm
FROM agent_sales
WHERE created_at > NOW() - INTERVAL '1 year'
GROUP BY user_id, year_month"
一旦有效,我能通过@ agent_monthly_performance.year_month调用吗?我知道我已经通过“AS”命令创建了不在我的模式中的新列。 (例如year_month)。
答案 0 :(得分:1)
MyModel.find_by_sql(query)
仍会继承模型实例。您可能需要进一步检查
答案 1 :(得分:1)
您可以使用ActiveRecord::Base.connection.execute
在rails
@agent_monthly_performance = ActiveRecord::Base.connection.execute("SELECT user_id AS user_id, to_char(created_at,'Mon-YY') AS year_month, sum(total_amount) AS amount, sum(total_lm) AS lm FROM agent_sales WHERE created_at > NOW() - INTERVAL '1 year' GROUP BY user_id, year_month").to_a
答案 2 :(得分:0)
你可以这样做:
sql = <<-SQL
SELECT user_id AS user_id,
to_char(created_at,'Mon-YY') AS year_month,
sum(total_amount) AS amount,
sum(total_lm) AS lm
FROM agent_sales
WHERE created_at > NOW() - INTERVAL '1 year'
GROUP BY user_id, year_month
SQL
SomeModel.find_by_sql(sql)