有沒有辦法避免過多的ActiveRecord呼叫? - Is there any way to avoid excess ActiveRecord calls? -开发者知识库

有沒有辦法避免過多的ActiveRecord呼叫? - Is there any way to avoid excess ActiveRecord calls? -开发者知识库,第1张

I have the following ActiveRecord call in a Rails controller ("filings#index"):

我在Rails控制器中調用了以下ActiveRecord(“文件#index”):

@filings = Filing.order("created_at DESC").limit(limit).offset(start).joins("LEFT OUTER JOIN companies ON companies.id=filings.company_id")

Each Filing belongs_to a Company. I would like to be able to access:

每個歸檔屬於公司。我希望能夠訪問:

@filings.first.company

Without having to make an additional SQL query as that was the entire purpose of completing an OUTER JOIN in the first place. However when I call @filings.first.company it performs an additional query:

無需進行額外的SQL查詢,因為這是首先完成OUTER JOIN的全部目的。但是,當我調用@ filings.first.company時,它會執行一個額外的查詢:

SELECT "companies".* FROM "companies" WHERE "companies"."id" = 989 LIMIT 1

How can I avoid this second query from taking place? Shouldn't the information already have been stored as a result of the initial query?

如何避免發生第二次查詢?作為初始查詢的結果,信息是否應該已存儲?

1 个解决方案

#1


1  

You need to include the information from the database:

您需要包含數據庫中的信息:

@filings = Filing.includes(:company).order("created_at DESC").offset(start).limit(limit)

hat tip to John Naegle and tharrison

向John Naegle和tharrison提示

最佳答案:

DABAN RP主题是一个优秀的主题,极致后台体验,无插件,集成会员系统
U19学习网站 » 有沒有辦法避免過多的ActiveRecord呼叫? - Is there any way to avoid excess ActiveRecord calls? -开发者知识库