Rails 4 - 如何使用ActiveRecords方法将“.find_by_sql”重写为查询?

时间:2016-03-19 16:53:16

标签: ruby-on-rails ruby join activerecord model

我坚持使用ActiveRecord的方法将我使用的查询(基本上是原始SQL)转换为查询。我试图转换它的原因是我需要使用范围。

find_by_sql("SELECT 
               COUNT(s.id) AS count_all,
               SUM(s.gross_profit) AS sum_gross_profit,   
               se.user_id,
               u.id,
               u.first_name,
               u.last_name,
               u.role
             FROM shipments s 
             INNER JOIN senders se ON se.id = s.sender_id 
             INNER JOIN users a ON a.id = se.user_id 
             WHERE ((#{status}) 
               AND (se.admin_id IS NOT NULL)
             GROUP BY se.user_id 
             ORDER BY count_all DESC")
  }

如何将所有sseu别名和2 INNER JOIN转换为ActiveRecord查询?

编辑:我尝试了什么:

select("COUNT(shipments.id) AS count_all,
        SUM(shipments.gross_profit) AS sum_gross_profit,   
        senders.admin_id,
        users.id,
        users.first_name,
        users.last_name,
        users.role")
.joins("INNER JOIN senders ON senders.id = shipments.sender_id 
        INNER JOIN users ON users.id = senders.user_id")
.where("((#{status}) 
          AND (senders.admin_id IS NOT NULL)")
.group("senders.user_id") 
.order("count_all DESC")

但这只返回如下输出:

{16=>41, 46=>34, 54=>2, 55=>1, 56=>1}:Hash

谢谢

1 个答案:

答案 0 :(得分:0)

看起来你最终想要的是User个实例,还有一些额外的属性。在这种情况下,ActiveRecord将使用FROM users,因此您需要稍微重写连接。因为一切都是INNER JOIN,这很容易。所以我会这样做:

User.select("COUNT(shipments.id) AS count_all,
        SUM(shipments.gross_profit) AS sum_gross_profit,   
        senders.admin_id,
        users.*")
.joins("INNER JOIN senders ON senders.user_id = users.id 
        INNER JOIN shipments ON shipments.sender_id = senders.id")
.where("(SOMETHING HERE)
          AND senders.admin_id IS NOT NULL")
.group("users.id") 
.order("count_all DESC")

我拿出了#{status},因为这看起来像是一个严重的安全漏洞。您应该学习如何使用where("foo = ?", bar)来阻止SQL注入。

即使在最初的SQL中也存在一些不匹配的parens,所以我清理了它们。