【问题标题】:Pluck query is working and select is not working in JOINS rails queryPluck 查询正在工作,而 select 在 JOINS rails 查询中不起作用
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

    • <5e2eca8><5e2ebe0><5e2ea78><5e2ea00><5e2e938><5e2e8c0>
    猜你喜欢
    • 2021-05-21
    • 1970-01-01
    • 2018-01-09
    • 2020-12-27
    • 1970-01-01
    • 2017-08-03
    • 2016-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多