在rails中使用原始sql来提升PG :: InFailedSqlTransaction

时间:2013-12-23 17:01:03

标签: sql ruby-on-rails postgresql

我有以下sql查询(从此article中选取:

SELECT
  date,
  coalesce(count,0) AS count
FROM
  generate_series(
      '2013-01-01 00:00'::timestamp,
      '2013-12-31 00:00'::timestamp,
      '1 day') AS date
  LEFT OUTER JOIN
  (SELECT
     date_trunc('day', users.created_at) as day,
     count(users.id) as count
   FROM users
   WHERE
     created_at >= '2013-01-01 00:00'
     AND created_at < '2013-12-31 00:00'
   GROUP BY day) results
    ON (date = results.day) ;

我想在rails中使用它,我想让时间显示为unix时间戳

在之前我使用的方法导致我的操作系统冻结:

  def yearly_chart
    start_year = Time.now.beginning_of_year.to_i*1000
    end_year = Time.now.to_i*1000
    all_tickets = Ticket.all

    count_for_year = (start_year..end_year).map do |year|
      [ year, all_tickets.select{|t| t.created_at.to_time.to_i*1000 == year }.count ]
    end
    @yearly_complaints = count_for_year
  end

我已经尝试了Find_by_sql,但它无法正常工作并提升:

PG::InFailedSqlTransaction: ERROR: current transaction is aborted, commands ignored until end of transaction block

此外,我在控制台中测试了ActiveRecord::Base.connection.execute,但也无效

1 个答案:

答案 0 :(得分:0)

使用find_by_sql

ActiveRecord用于组装冗余&amp;模式之外的平淡无奇的SQL查询。您的查询既不冗余也不直接,因此只需发送您已经发明的原始查询。