【发布时间】:2014-11-14 11:16:08
【问题描述】:
我有 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 等效的 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)>]]
我应该如何更改 select 的 rails 查询?
【问题讨论】:
标签: mysql ruby-on-rails ruby-on-rails-4