Pluck查询正在运行,并且选择在JOINS rails查询中不起作用

时间:2014-11-14 11:16:08

标签: mysql ruby-on-rails ruby-on-rails-4

我有2个具有has_many关系的模型。

class CurrencyExchange < ActiveRecord::Base
  has_many :exchange_market_prices
end

class ExchangeMarketPrice < ActiveRecord::Base
  belongs_to :currency_exchange
end

我正在尝试以下sql输出

mysql> select ce.code, emp.buy_price, emp.sell_price  from currency_exchanges ce inner join exchange_market_prices emp on ce.id=emp.currency_exchange_id;

+----------+--------------+--------------+
| code     | buy_price    | sell_price   |
+----------+--------------+--------------+
| cryptsy  | 392.96862470 | 390.74000000 |
| bter     | 392.00300000 | 392.00200164 |
| bitstamp | 393.78000000 | 393.77000000 |
| btce     | 388.82300000 | 388.56400000 |
| ccex     | 412.00000000 | 370.20000000 |
+----------+--------------+--------------+
5 rows in set (0.30 sec)

使用select(Not working)

进行等效rails查询
$ rails c -e local
    Loading local environment (Rails 4.1.7)
    2.1.3 :034 >  emps = CurrencyExchange.joins(:exchange_market_prices).select("currency_exchanges.code, exchange_market_prices.buy_price,  exchange_market_prices.sell_price")
     => #<ActiveRecord::Relation [#<CurrencyExchange id: nil, code: "cryptsy">, #<CurrencyExchange id: nil, code: "bter">, #<CurrencyExchange id: nil, code: "bitstamp">, #<CurrencyExchange id: nil, code: "btce">, #<CurrencyExchange id: nil, code: "ccex">]> 

当我尝试采摘(工作)时

  2.1.3 :033 >    emps = CurrencyExchange.joins(:exchange_market_prices).pluck("currency_exchanges.code, exchange_market_prices.buy_price,  exchange_market_prices.sell_price")
     => [["cryptsy", #<BigDecimal:5e7b6c0,'0.3977857849 4E3',18(27)>, #<BigDecimal:5e7b648,'0.3954137660 3E3',18(27)>], ["bter", #<BigDecimal:5e7b580,'0.392003E3',18(27)>, #<BigDecimal:5e7b508,'0.3920020016 4E3',18(27)>], ["bitstamp", #<BigDecimal:5e7b440,'0.4E3',9(27)>, #<BigDecimal:5e7b3c8,'0.39901E3',18(27)>], ["btce", #<BigDecimal:5e7b300,'0.395714E3',18(27)>, #<BigDecimal:5e7b288,'0.394E3',9(27)>], ["ccex", #<BigDecimal:5e7b1c0,'0.412E3',9(27)>, #<BigDecimal:5e7b148,'0.3702E3',18(27)>]]

如何更改选择

的rails查询

1 个答案:

答案 0 :(得分:1)

使用#collect方法时,您需要使用#select。因为#select会在ActiveRecord::Relation对象中为您提供 wrap 的结果。您需要迭代,并收集所有必需的属性。

emps.collect do |rec| 
   { :sell_price => rec.sell_price, :buy_price => rec.buy_price, :code => rec.code }
end