2014-01-30 36 views
0

在我的Ruby on Rails應用程序下面的代碼(紅寶石2.1來說,Rails 4.0.2)返回ActiveRecord的SQL語句不返回正確的數據

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沒有返回預期的結果?錯誤還是限制?

+0

嘗試a.to_a不知道,但可能是它幫助 –

+0

a.to_a返回相同的結果 – KKK

回答

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屬性。確切的解釋是在文檔 http://guides.rubyonrails.org/active_record_querying.html#selecting-specific-fields

+0

真棒,即做到了。 – KKK