2012-03-04 5 views
1

私はRuby on Rails 3.1を使用していますが、 "関連する"レコードと "関連する"レコード(ActiveRecord::Associations)の両方を効率的な方法で取得するためにSQLクエリを改善しようとしていますので、 "N +問題 "となります。私は両方のcategoriescategory_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 
+1

正確にどのクエリを最適化しますか? – iltempo

+0

@iltempo - 質問を更新しました。 – Backo

答えて

0

。パフォーマンスのために、外部キーにインデックスが付いていることを確認してください。

しかし、私はなぜ「category_relationships」エンティティが存在するのか、なぜこれがhas_and_belongs_toな状況ではないのか不思議です。

は、コンソールを見れば、あなたはまだ

Category.includes(:article_relationships => :articles).first 

を行うことができ、あなたの変更質問1として

を更新しました(またはテール・ログ/開発)あなたが関連を呼び出すときことがわかりますキャッシュされた値に当てられ、あなたは金色になります。

しかし、あなたがHasとBelongs To Manyを使っていない理由はまだ不思議です。

+0

'Article.includes(:category_relationships =>:categories).where(:user_id => 1)'のような 'where'メソッドを含むいくつかのステートメントを使用すれば'?私は同じ結果を得る(パフォーマンスに関して)? * BTW *: 'includes()'は実際にどのように動作しますか? – Backo

+0

私は質問を更新しました。 – Backo

関連する問題