ActiveRecord SQL语句未返回正确的数据

时间:2014-01-30 09:55:48

标签: mysql ruby-on-rails activerecord

我的Ruby on Rails应用程序(Ruby 2.1,Rails 4.0.2)中的以下代码返回

a = Order.select('if(currency1_id=3,unitprice,1/unitprice) as uu,sum(if(currency1_id=3,open_quantity,open_quantity*unitprice)) as qq').where("((currency1_id=? and currency2_id=? and otype = 0) or (otype = 1 and currency1_id=? and currency2_id=?))",c1.id,c2.id,c2.id,c1.id).group('uu').order('uu desc').limit(20)
=> #<ActiveRecord::Relation [#<Order id: nil>, #<Order id: nil>, #<Order id: nil>, #<Order id: nil>, #<Order id: nil>, #<Order id: nil>, #<Order id: nil>, #<Order id: nil>, #<Order id: nil>, #<Order id: nil>, ...]> 

所以我跑

a.to_sql

给了我

=> "SELECT  if(currency1_id=3,unitprice,1/unitprice) as uu,sum(if(currency1_id=3,open_quantity,open_quantity*unitprice)) as qq FROM `orders`  WHERE (((currency1_id=3 and currency2_id=1 and otype = 0) or (otype = 1 and currency1_id=1 and currency2_id=3))) GROUP BY uu  ORDER BY uu desc LIMIT 20" 

我接受了这个SQL语句并直接在MySQL中运行,令我惊讶的是,与Rails不同,它正好重新确定了我期望它返回的数据。

mysql> SELECT  if(currency1_id=3,unitprice,1/unitprice) as uu,sum(if(currency1_id=3,open_quantity,open_quantity*unitprice)) as qq FROM `orders`  WHERE (((currency1_id=3 and currency2_id=1 and otype = 0) or (otype = 1 and currency1_id=1 and currency2_id=3))) GROUP BY uu  ORDER BY uu desc LIMIT 20;

    +------------+----------------------+
    | uu         | qq                   |
    +------------+----------------------+
    | 0.02638201 |   0.2751620500000000 |
    | 0.02638200 |   0.5000000000000000 |
    | 0.02616701 |  13.7539900000000000 |
    | 0.02616700 |   1.0000000000000000 |
    | 0.02610030 |   0.3421014700000000 |
    | 0.02610000 |   2.0000000000000000 |
    | 0.02600000 |  10.1530000000000000 |
    | 0.02597364 |   7.9000000000000000 |
    | 0.02596814 |   0.2747080000000000 |
    | 0.02591992 |   0.3999690000000000 |
    | 0.02591991 |   1.9183083000000000 |
    | 0.02591900 |  11.0000000000000000 |
    | 0.02591002 |  90.0000000000000000 |
    | 0.02591001 |   0.3667208155574714 |
    | 0.02551036 |   1.0000000000000000 |
    | 0.02550001 |  42.0000000000000000 |
    | 0.02550000 | 108.0606277900000000 |
    | 0.02540107 |   3.0000000000000000 |
    | 0.02540000 |   0.0500000000000000 |
    | 0.02520000 |  10.0000000000000000 |
    +------------+----------------------+
    20 rows in set (0.00 sec)

为什么ActiveRecord没有返回预期的结果?错误或限制?

1 个答案:

答案 0 :(得分:1)

ActiveRecord正在按照您的要求去做。它从数据库中获取与使用SQL时相同的数据。唯一的区别是它如何返回它。

在运行ActiveRecord查询后尝试以下操作

a.map {|order| [order.uu, order.qq] }

这应该为您提供一个数组数组,表示SQL中的值

[[0.02638201, 0.2751620500000000],
 [0.02638200, 0.5000000000000000],
 [0.02616701, 13.7539900000000000],
 .....]

ActiveRecord基本上返回一个只有uu和pp属性的Orders数组。确切的解释是在文档中 http://guides.rubyonrails.org/active_record_querying.html#selecting-specific-fields