如何将postgres查询转换为rails对象?

时间:2017-09-13 11:17:33

标签: ruby-on-rails postgresql

下面的代码用作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)。

3 个答案:

答案 0 :(得分:1)

MyModel.find_by_sql(query)仍会继承模型实例。您可能需要进一步检查

答案 1 :(得分:1)

您可以使用ActiveRecord::Base.connection.execute在rails

中执行行sql查询
@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)