有Project模型和ProjectGroup模型,ProjectGroup模型继承于Project模型。
# Project
class Project < ActiveRecord::Base
has_and_belongs_to_many :child_projects
end
# ProjectGroup inherit Project
class ProjectGroup < Project
has_and_belongs_to_many :projects
has_and_belongs_to_many :docs
# ProjectGroup is Project.where(:type => ''ProjectGroup)
end
项目模型 has_and_belongs_to_many 文档,我想按文档数量订购项目模型和 ProjectGroup(as Project.where(:type => 'ProjectGroup'))
Project 模型的文档数是与项目相关的文档数,另一方面,ProjectGroup 模型的文档数是与与 ProjectGroup 相关的所有项目相关的文档数。
我为每个模型编写了按文档计数排序的范围,这些仅在连接条件上有所不同。
我知道 joins 方法太复杂了,所以如果它困扰你,你可以忽略这些方法。
# Project model
scope :order_pmdocs_count,
joins("
LEFT OUTER JOIN projects_sprojects ON projects_sprojects.sproject_id = projects.id
LEFT OUTER JOIN docs_projects ON docs_projects.project_id IN (projects_sprojects.project_id)
LEFT OUTER JOIN docs ON docs.id = docs_projects.doc_id AND docs.sourcedb = 'PubMed'
").group('projects.id').order("count(docs.id) DESC")
# ProjectGroup model
scope :order_docs_count,
joins("
LEFT OUTER JOIN projects_sprojects ON projects_sprojects.sproject_id = projects.id
LEFT OUTER JOIN docs_projects ON docs_projects.project_id IN (projects_sprojects.project_id)
LEFT OUTER JOIN docs ON docs.id = docs_projects.doc_id AND docs.sourcedb = 'PubMed'
").group('projects.id').order("count(docs.id) DESC")
是否可以通过文档数量来切换或混合这些连接方法并订购 Project 模型和 ProjectGroup 模型(作为 Project 模型)?
还是有另一种方法可以通过每种计数方法来订购这些模型?