【发布时间】:2012-05-08 12:32:53
【问题描述】:
在我的应用文章中有很多子或父文章通过自引用加入模型article_relationships
class Article < ActiveRecord::Base
has_many :parent_child_relationships,
:class_name => "ArticleRelationship",
:foreign_key => :child_id,
:dependent => :destroy
has_many :parents,
:through => :parent_child_relationships,
:source => :parent
has_many :child_parent_relationships,
:class_name => "ArticleRelationship",
:foreign_key => :parent_id,
:dependent => :destroy
has_many :children,
:through => :child_parent_relationships,
:source => :child
end
class ArticleRelationship < ActiveRecord::Base
belongs_to :parent, :class_name => "Article"
belongs_to :child, :class_name => "Article"
end
我有一个关于 article_relationships 的相当复杂的查询,它深入到文章表中
ArticleRelationship.joins(:parent, :child).where("((articles.type IN (:parent_article_type) AND parent_id IN (:ids)) OR (children_article_relationships.type IN (:child_article_type) AND child_id IN (:ids)) AND (article_relationships.created_at > :date OR article_relationships.updated_at > :date))", {:parent_article_type => "Emotion", :child_article_type => "Gateway", :ids => [1,2,3,4], :date => "2010-01-01"})
有什么方法可以有效地索引它吗?
【问题讨论】:
-
对于复杂查询,请使用
squeelgem。它通过not_in、like_any和其他很酷的功能扩展了您的语法。值得尝试。 github.com/ernie/squeel
标签: mysql ruby-on-rails indexing