`to_a`避免重新运行查询?

时间:2018-03-23 13:00:18

标签: ruby-on-rails ruby activerecord

我在控制台中注意到to_aActiveRecord_Relation方法的异常用户。我将在下面复制它:

从表格中选择变量a

a = Crypto::ExchangeQuotation.all
[DEBUG]   Crypto::ExchangeQuotation Load (121.1ms)  SELECT  "crypto_exchange_quotations".* FROM "crypto_exchange_quotations" LIMIT $1  [["LIMIT", 11]]

致电a

2.4.1 :003 > a
[DEBUG]   Crypto::ExchangeQuotation Load (0.8ms)  SELECT  "crypto_exchange_quotations".* FROM "crypto_exchange_quotations" LIMIT $1  [["LIMIT", 11]]

a到数组:

2.4.1 :004 > a.to_a
[DEBUG]   Crypto::ExchangeQuotation Load (0.9ms)  SELECT "crypto_exchange_quotations".* FROM "crypto_exchange_quotations"

再次致电a

2.4.1 :005 > a
 => #<ActiveRecord::Relation [#<Crypto::ExchangeQuotation id: 1, exchange_code: "ARN", base_currency_code: "BRL", currency_code: "BTC", origin: "bitvalor", created_at: "2018-03-15 23:24:06", updated_at: "2018-03-15 23:24:06", buy: 17810.0, sell: 17810.0>,

在变量中调用to_a,之后再次调用它真的避免再次重新运行查询吗?如果是,为什么?因为a中返回的内容仍然是ActiveRecord_Relation

1 个答案:

答案 0 :(得分:2)

调用to_a不会改变基础对象,但它会复制它并将其作为数组返回。在这里查看to_a的广告代码:

def to_a
  records.dup
end

要真正将其更改为数组,您必须覆盖变量a

a = a.to_a