2012-03-04 83 views
1

我正在使用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()法)我想同時檢索categoriescategory_relationships,或兩者articlesarticle_relationships

我該怎麼做?


P.S:我提高查詢類似如下:

@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 2012-03-04 15:55:04

+0

@iltempo - 我更新了問題。 – Backo 2012-03-04 17:05:30

回答

0

你可以做

Article.includes(:category_relationships => :categories).find(1) 

這將這種減少3個查詢(1爲每個表)。爲了提高性能,還要確保你的外鍵有一個索引。

但總的來說,我很好奇爲什麼「category_relationships」實體存在,爲什麼這不是一個has_and_belongs_to的情況?

更新

根據你的改變的問題,你仍然可以做

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

如果你看控制檯(或尾部日誌/開發),你會看到,當你調用協會,它會達到緩存的值,而你是金。

但我仍然好奇你爲什麼不使用Has和Belongs To Many關聯。

+0

如果我使用某種語句,包括'where'方法,如:'Article.includes(:category_relationships =>:categories).where(:user_id => 1)'?我得到相同的結果(關於表現)? *順便說一句*:包含()是如何工作的? – Backo 2012-03-04 17:00:57

+0

我更新了問題。 – Backo 2012-03-04 17:05:39