私はRuby on Rails 3.1を使用していますが、 "関連する"レコードと "関連する"レコード(ActiveRecord::Associations
)の両方を効率的な方法で取得するためにSQLクエリを改善しようとしていますので、 "N +問題 "となります。私は両方のcategories
とcategory_relationships
を取得したい(多分Ruby on Railsにincludes()
方法を用いることで、それは「パフォーマンスの道」で、ある)SQLクエリのカップルで「関連」レコードと「関連スルー」レコードの両方を効率的に取得するにはどうすればよいですか?
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
:それは私が持っている、です,またはその両方articles
およびarticle_relationships
。
どうすればいいですか?
P.S:私は以下のようなクエリを改善しています:あなたは3つのクエリ(各テーブルの1)にこれを削減する
Article.includes(:category_relationships => :categories).find(1)
を行うことができます
@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
正確にどのクエリを最適化しますか? – iltempo
@iltempo - 質問を更新しました。 – Backo