[英]How to retrieve both “associated” records and “associated through” records in a performant way?
我正在使用Ruby on Rails 3.1,並且嘗試改進SQL查詢,以便以一種有效的方式檢索“關聯的”記錄和“關聯的通過”記錄( ActiveRecord::Associations
),以避免出現“ N +1個查詢”問題 ”。 也就是說,我有:
class Article < ActiveRecord::Base
has_many :category_relationships
has_many :categories,
:through => :category_relationships
end
class Category < ActiveRecord::Base
has_many :article_relationships
has_many :articles,
:through => :article_relationships
end
在一對夫婦的SQL查詢(即,在“性能方法”,也許用on Rails的Ruby的includes()
方法) 我想找回這兩個categories
和category_relationships
, 或兩者articles
和article_relationships
。
我該怎么做?
PS:我正在改進如下查詢:
@category = Category.first
articles = @category.articles.where(:user_id => @current_user.id)
articles.each do |article|
# Note: In this example the 'inspect' method is just a method to "trigger" the
# "eager loading" functionalities
article.category_relationships.inspect
end
你可以做
Article.includes(:category_relationships => :categories).find(1)
這將減少到3個查詢(每個表1個)。 為了提高性能,還請確保您的外鍵具有索引。
但是總的來說,我很好奇為什么“ category_relationships”實體根本存在,為什么這不是has_and_belongs_to這樣的情況?
更新
根據您更改的問題,您仍然可以
Category.includes(:article_relationships => :articles).first
如果您觀看控制台(或尾部日志/開發),您會看到在調用關聯時,它將達到緩存的值,因此您很高興。
但是我仍然很好奇為什么您不使用“具有並屬於許多人”協會。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.