我正在使用 Rails 3.2.8 进行开发,并希望通过多个关系计数的总和来订购模型。
有一个 Doc 模型,它有许多 subcatrels 和 subinsrels,两者都是 Relation 模型(不是模型关系,一个名为“Relation”的模型)。
文档.rb
class Doc < ActiveRecord::Base
has_many :denotations
has_many :instances, :through => :denotations
has_many :subcatrels, :class_name => 'Relation', :through => :denotations, :source => :subrels
has_many :subinsrels, :class_name => 'Relation', :through => :instances, :source => :subrels
scope :pmdocs, where(:sourcedb => 'PubMed')
.
.
end
我想通过计数 subcatrels 和 subinsrels 的总和来订购 Doc 模型。
我在下面尝试订购范围 pmdocs。
Doc.pmdocs.includes([:subcatrels, :subinsrels]).group('docs.id').order('(count(subcatrels.id) + count(subinsrels.id)) DESC')
并在下面出现错误。
PG::Error: ERROR: missing FROM-clause entry for table "subcatrels"
LINE 1: SELECT DISTINCT "docs".id, (count(subcatrels.id) + count(su...
: SELECT DISTINCT "docs".id, (count(subcatrels.id) + count(subinsrels.id)) AS alias_0 FROM "docs" LEFT OUTER JOIN "denotations" ON "denotations"."doc_id" = "docs"."id" LEFT OUTER JOIN "relations" ON "relations"."subj_id" = "denotations"."id" AND "relations"."subj_type" = 'Denotation' LEFT OUTER JOIN "denotations" "denotations_docs_join" ON "denotations_docs_join"."doc_id" = "docs"."id" LEFT OUTER JOIN "instances" ON "instances"."obj_id" = "denotations_docs_join"."id" LEFT OUTER JOIN "relations" "subinsrels_docs" ON "subinsrels_docs"."subj_id" = "instances"."id" AND "subinsrels_docs"."subj_type" = 'Instance' WHERE "docs"."sourcedb" = 'PubMed' GROUP BY docs.id ORDER BY (count(subcatrels.id) + count(subinsrels.id)) DESC LIMIT 10 OFFSET 0
如何通过计数 subcatrels 和 subinsrels 的总和来订购 Doc 模型?
其他模型源代码如下。
外延.rb
class Denotation < ActiveRecord::Base
belongs_to :doc
has_many :instances, :foreign_key => "obj_id", :dependent => :destroy
has_many :subrels, :class_name => 'Relation', :as => :subj, :dependent => :destroy
has_many :objrels, :class_name => 'Relation', :as => :obj, :dependent => :destroy
.
.
end
实例.rb
class Instance < ActiveRecord::Base
belongs_to :obj, :class_name => 'Denotation'
has_many :subrels, :class_name => 'Relation', :as => :subj, :dependent => :destroy
has_many :objrels, :class_name => 'Relation', :as => :obj, :dependent => :destroy
.
.
end
协会形象