包含的活动记录查询不包括

时间:2010-09-22 18:03:46

标签: ruby-on-rails activerecord ruby-on-rails-3

我有这个'查询'

    @product_collections = ProductCollection.
        #includes(:products). #does not do anything
        joins(:products). #this at least gives me the products (in articles table)
        group("tags.id").
        where("articles.category_id = ?", @category.id).
        where("articles.available = ?", true).
        order('tags.name asc')

这会生成以下sql

SELECT     "tags".* FROM       "tags"  
INNER JOIN "article_taggings" ON "tags"."id" = "article_taggings"."tag_id" 
INNER JOIN "articles" ON "articles"."id" = "article_taggings"."article_id" 
WHERE     ("tags"."type" = 'ProductCollection') 
AND (articles.category_id = 1) 
AND (articles.available = 't') 
GROUP BY  tags.id 
ORDER BY  tags.name asc

我怎样才能让产品在一个(或仅一秒钟)内完成?

型号:

class Article < ActiveRecord::Base
  has_many :article_taggings
  has_many :tags, :through => :article_taggings
end

class Product < Article
  belongs_to :category
  has_many :product_collections, :through => :article_taggings, :source => :tag
end

class ArticleTagging < ActiveRecord::Base
    belongs_to :article
    belongs_to :tag
end

class Tag < ActiveRecord::Base
  has_many :article_taggings
  has_many :articles, :through => :article_taggings
  has_and_belongs_to_many :web_pages
end

class ProductCollection < Tag
  has_many :products, :through => :article_taggings, :source => :article
end

1 个答案:

答案 0 :(得分:1)

您需要在加入后放置包含。这将解决问题。