我在控制台中注意到,to_a方法在ActiveRecord_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。
发布于 2018-03-23 14:28:49
调用to_a并不会改变基本对象,但它会复制这个对象并将其作为数组返回。下面看一下to_a的广告代码:
def to_a
records.dup
end若要真正将其更改为数组,必须重写变量a
a = a.to_ahttps://stackoverflow.com/questions/49450274
复制相似问题